Reputation: 264
new Promise(resolve => {
resolve(1)
}).then(a => console.log(a))
Promise.resolve().then(() => console.log(2))
will print 1, 2
Promise.resolve().then(() => console.log(2))
new Promise(resolve => {
resolve(1)
}).then(a => console.log(a))
will print 2, 1
but i don't understand why
new Promise(resolve => {
resolve(1)
Promise.resolve().then(() => console.log(2))
}).then(a => console.log(a))
will print 2, 1
Upvotes: 2
Views: 326
Reputation: 3443
Promise.resolve
will return an immediately resolved promise, and calling new Promise(resolve => { resolve() })
will also resolve right away. Just because its a promise does not make it async if you didn't do anything asynchronous with it, like throw it in a timeout, interval, etc. So:
// this resolves when called and logs first (1)
new Promise(resolve => {
resolve(1)
}).then(a => console.log(a))
// this resolves and logs immediately (2)
Promise.resolve().then(() => console.log(2))
// this resolves immediately (2)
Promise.resolve().then(() => console.log(2))
// this resolves when called (1)
new Promise(resolve => {
resolve(1)
}).then(a => console.log(a))
new Promise(resolve => {
// this passes 1 to the then chained to this promise,
// which won't run until this function body is done.
resolve(1)
// this resolves immediately and logs (2)
Promise.resolve().then(() => console.log(2))
// now we drop into then and it logs (1)
}).then(a => console.log(a))
See here for more details on Promise.resolve
.
Upvotes: 2
Reputation: 2052
Promises
work by using the Event Loop, so any code calling promises will happen in order of resolution, regardless of order of creation.
const test = Promise.resolve(1).then(console.log) // pushes chain A to loop, [A]
Promise.resolve(2).then(console.log) // pushes chain B onto loop, [A,B]
test.then(() => 3).then(console.log) // pushes chain C onto loop, [A, B, C]
//first loop resolution, 1, then console.log
//second loop resolution, 2, then console.log
//third loop resolution, 3, then console.log
Even though test
was made before chain B
, Chain C
happens AFTER B
because the event loop is a first in, first out model. This is because Promise
s are asynchronous
meaning they will resolve in the order received by the Event Loop and since resolve pushes onto the event loop without waiting on anything, it is immediately there.
fetch('https://google.com').then(() => console.log(1)) // waits for networks
Promise.resolve(2).then(console.log) // pushes chain B onto loop [B]
// B resolves, 2, console.log, loop empty []
// fetch returns finally, pushes A onto loop [A]
// A resolves, 1, console.log, loop empty []
What you're seeing is a race condition of immediately resolving promises, meaning that they will resolve in the imperative order executed through the chains.
Upvotes: 2