new Promise(resolve => {
resolve(1)
}).then(a => console.log(a))
Promise.resolve().then(() => console.log(2))将打印% 1、%2
Promise.resolve().then(() => console.log(2))
new Promise(resolve => {
resolve(1)
}).then(a => console.log(a))将打印% 2,%1
但我不明白为什么
new Promise(resolve => {
resolve(1)
Promise.resolve().then(() => console.log(2))
}).then(a => console.log(a))将打印% 2,%1
发布于 2019-09-04 12:06:23
Promise.resolve将返回一个立即解析的promise,调用new Promise(resolve => { resolve() })也将立即解析。如果你不对它做任何异步操作,比如在超时、间隔等情况下抛出它,那么它的承诺并不意味着它是异步的:
// 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))有关Promise.resolve的详细信息,请参阅here。
发布于 2019-09-04 12:03:20
Promises通过使用事件循环工作,因此任何调用promises的代码都将按照解析的顺序发生,而不考虑创建的顺序。
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尽管test是在chain B之前创建的,但Chain C发生在B之后,因为事件循环是先入先出模型。这是因为Promise是asynchronous,这意味着它们将按照事件循环接收到的顺序进行解析,并且由于resolve在不等待任何东西的情况下推送到事件循环上,因此它会立即出现。
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 []您看到的是立即解析承诺的竞争条件,这意味着它们将以通过链执行的命令顺序解析。
https://stackoverflow.com/questions/57781257
复制相似问题