0

I have the below javascript code that I wrote to understand the async behavior

console.log(1);

let myPromise = () => {

    //return Promise.resolve("success");
    return new Promise((resolve, reject) => {
        for (let i = 0; i < 10000000; i++) {
            let p = i ** 2;
        }
        console.log('loop complete');
        resolve('success');
    })
}

console.log(2);

myPromise()
    .then((m) => {
        console.log(m);
        return myPromise()
    })
    .then((m) => console.log(m))
    .catch((e) => console.log(e))

console.log(3);

My expected output is

1
2
loop complete
success
loop complete
success
3

since .then() chaining is synchronous (or it is not ). But the actual output is

1
2
loop complete
3
success
loop complete
success

I can't understand why the output is like that? Can anyone explain the behavior?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    The `for` loop and `myPromise` are still executed synchronously. Just because there is a promise, doesn't mean execution is carried out asynchronously. Creating promises does not create any new threads or similar. They are just a notification mechanism. – VLAZ Apr 19 '21 at 14:46
  • 2
    Just so summarize briefly, there are two things here of note: 1. The function you pass to `new Promise` (the *promise executor* function) is called **synchronously**. Its job is to *start* an asynchronous process and set up a means of knowing when that process is complete, so it can call `resolve` or `reject` to settle the promise. 2. You're right, calling `then` is synchronous, which is a key part of why you see what you do above. It's the call to `then` that's synchronous, **not** the call to the handler function you pass to `then`; they're called later (if appropriate). – T.J. Crowder Apr 19 '21 at 14:54
  • 2
    So there's no reason for `new Promise` above, because it doesn't start any asynchronous work. To play with promises to understand them better, a good asynchronous thing to start in the promise is a timer: `new Promise((resolve, reject) => { setTimeout(() => { /* ...call resolve or reject... */ }, someNumberOfMilliseconds); }` – T.J. Crowder Apr 19 '21 at 14:55
  • Thank you for the clarification, I thought anything I wrap inside Promise is executed asynchronously @T.J.Crowder – Probhakar Sarkar Apr 19 '21 at 15:13
  • 1
    @ProbhakarSarkar - You're not the only one. :-) Nope, promises are a means of *observing* an asynchronous process and reporting on its completion. They don't make anything asynchronous themselves (except that calls to promise callbacks will always be made asynchronously). FWW, I go into promises and `async` functions in a fair bit of detail in Chapters 8 and 9 of my recent book *JavaScript: The New Toys*. Links in my profile if you're interested. – T.J. Crowder Apr 19 '21 at 15:21

0 Answers0