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?

Jamiec
  • 133,658
  • 13
  • 134
  • 193
reddur
  • 61
  • 1
  • 6
  • 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](https://stackoverflow.com/q/21607692/438273) a question to get started. – jsejcksn Jul 28 '22 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) – Jamiec Jul 28 '22 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. – Jaood_xD Jul 28 '22 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. – Bergi Jul 28 '22 at 15:18

0 Answers0