0

I was wondering how promises are resolved in javascript. If anyone could explain how promises in the code below are processed. I understand that js compiler maintains a separate queue for promises.

const promisePrint = (n) =>{
    return new Promise(res=>{
        console.log(n, 'inside')
        res(n)
    })
}

(async()=>{
    console.log(await promisePrint(33), 'outside')
    console.log(await Promise.resolve(10))
})()

Promise.resolve()
.then(()=>console.log(1))
.then(()=>console.log(2))
.then(()=>console.log(3))

Output:

33 'inside'
1
2
33 'outside'
3
10

some resources referred: https://www.youtube.com/playlist?list=PLillGF-Rfqbars4vKNtpcWVDUpVOVTlgB

And why is 33 'outside' taking so long to be resolved?

4
  • The best way to think about any given promise is that it will simply resolve later / not now. (I'm in no way discouraging you from exploring the spec or specific JS engine implementations: rather, I'm just offering practical advice. Stay curious!) Here's a question to get started. Commented Jul 28, 2022 at 14:51
  • 1
    Ive made your code runnable, and it's worth noting that I get a different order of output, and therein is sort of your answer, with code like this the order of results is somewhat deendent on the implemnentation (mine is chrome on windows) Commented Jul 28, 2022 at 15:01
  • It's not consistent behavior depends on environment, version of node and so on. For example your code runned on playcode.io gives you both 'inside' and 'outside' together. Commented Jul 28, 2022 at 15:01
  • @Jaood_xD It does not depend on the environment or anything, just on the version of the spec that your node version implements (there were optimisations at some point that all engines implement). But yes, it should be considered an implementation detail and is subject to change, nothing to rely on. Commented Jul 28, 2022 at 15:18

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.