Search code examples
javascriptfetch

What does Reponse represent in Promise<Reponse> in Javascript?


I'm learning about the fetch method in Javascript and I when I say

fetch.("url").then(r => {if(r.status!==200)doSomething();} )

and when I hover over "fetch" it says that it returns Promise<Response>, and the r parameter in the function in "then" is a Response.

My question is: what does the type in <> mean? I know that in C++ it represents a template, in this case a class, but how does the function know that the "r" parameter is a Response?


Solution

  • What does Reponse represent in Promise in Javascript?

    Nothing. Promise<Response> is not valid Javascript syntax so it does not mean anything.

    When I hover over "fetch" it says that it returns Promise, and the r parameter in the function in "then" is a Response... My question is: what does the type in <> mean?

    The javascript programming language itself does not come with an editor or IDE. Most people write javascript in their favorite text editor. You will need to look at the documentation of your code editor or IDE to know what the popup means.

    However we can guess what it means. <> is not valid javascript syntax so the programmer who developed the code editor probably took inspiration from C++/Java. My guess is it means the same thing in C++/Java - that being that the Promise is a template/generic (it is not really in javascript since there is no such thing) if you look at it from a C++/Java programmer's point of view and it will compile to an object who's .then() method expects a function who's argument is of the type in <> (similar to Futures in C++ and Java).

    How does the function know that the "r" parameter is a Response?

    It does not. The programmer who wrote the Promise interface expect you to pass a function who accepts one argument to its .then() method. The programmer's code will then call the function you pass to .then() and pass it the Response object.

    Here's an example. Let me write this simple function:

    function sayHello (formatter) {
        console.log(formatter("Hello World"));
    }
    

    Now let's use the function above:

    sayHello(h => {
        return "This is a " + h.toUpperCase() + " program";
    })
    // output = This is a HELLO WORLD program
    

    Your question is how does the sayHello function know that the h parameter is a string who's value is "Hello World"?

    The answer is simple, It's because I, the programmer who wrote the sayHello() function, pass it to you.

    How would you know that h is the string "Hello World"? Well, hopefully I would have written some documentation somewhere for you to read.

    So how would you know what is the value of r in your code? You need to read the documentation: https://developer.mozilla.org/en-US/docs/Web/API/fetch. Specifically the first sentence in the second paragraph:

    The promise resolves to the Response object representing the response to your request.