1

I am new to JS and was learning promises and how they are used in JS and I would like to ask some questions. Firstly, if you look at the code below:

var makeRequest = function (url, method) {

    // Create the XHR request
    var request = new XMLHttpRequest();

    // Return it as a Promise
    return new Promise(function (resolve, reject) {

        // Setup our listener to process compeleted requests
        request.onreadystatechange = function () {

            // Only run if the request is complete
            if (request.readyState !== 4) return;

            // Process the response
            if (request.status >= 200 && request.status < 300) {
                // If successful
                resolve(request);
            } else {
                // If failed
                reject({
                    status: request.status,
                    statusText: request.statusText
                });
            }

        };

        // Setup our HTTP request
        request.open(method || 'GET', url, true);

        // Send the request
        request.send();

    });
};

makeRequest('https://some-url.com/posts')
    .then(function (posts) {
        console.log('Success!', posts);
    })
    .catch(function (error) {
        console.log('Something went wrong', error);
    });

The first question I would like to ask is about callback of then(), I mean the callback that we use inside then() like then((data)=>{console.log(data)}). Can I imagine it as asynchronous callback that we used before promises, that is, the callback that awaited until asynchronous, for example, xhr object finishes and returns result. And, in promise the callback of then() waits until promise gives result which MEANS PROMISE HELPS TO DECOUPLE CALLBACK FUNCTION FROM ASYNCHRONOUS OPERATION. The second question, is the callback of then() asynchronous, I mean, is it also run via event loop as well as asynchronous code that promise wraps or the code, that promise wraps e.g xhr object, are the only asynchrony in promises? The third question, when we say function returns promise, does it mean that promise is returned right away regardless of whether it was resolved or not. Can I imagine it like this when function returns promise, that returned promise kinda tells us "please wait a bit and I promise I will provide you with the result which you can handle with then()"

1 Answers1

2

Can I imagine a then callback as an asynchronous callback, like the ones we used before promises?

Yes. It's still "just" a callback that is called aynchronously when the xhr object finishes and has its result available.

PROMISE HELPS TO DECOUPLE CALLBACK FUNCTION FROM ASYNCHRONOUS OPERATION

Yes, exactly. You don't need to know any more where exactly the result comes from and how to get it - you just have a promise and can use it to wait for the result.

When a function returns a promise, that returned promise kinda tells us "please wait a bit and I promise I will provide you with the result which you can handle with then()"

Precisely.

Is the callback of then() asynchronous, I mean, is it also run via event loop as well?

Yes. Apart from the XHR resolving the promise asynchronously, also all then callback are guaranteed to be called asynchronously.

When we say a function returns a promise, does it mean that the promise is returned right away regardless of whether it was resolved or not?

Yes. It's an observable handle.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • You cannot imagine how I am grateful to you for your explanation and for your promise evangelism. I am really interested in understanding how promises work but you can kill me I still cannot get why callback in then() is asynchronous. Since it is uncomfortable for me to again ask for explanation, I would be grateful if you could recommend me a book or article clearly explaining promises. Yes, I made my research and majority of articles on the WEB explains promises superficially. – user11807902 Jul 26 '19 at 05:53
  • Sorry, I can't recommend any articles or books because I've learned everything from looking at the implementation details (and their discussions). What exactly do you not understand about the callback being asynchronous? Would you expect it to be synchronous? – Bergi Jul 26 '19 at 13:54