Console.log() 在承诺中的奇怪行为
Weird Behavior from Console.log() in promises
所以我正在使用 promise 做一些工作,当我在 promise 中使用 console.log() 时出现了一些奇怪的行为。
代码
function doSomething(msg){
return new Promise(
(myresolve, myreject) => {
setTimeout(
() => {
console.log(msg);
console.log('In the promise')
myresolve();
},
1000);
});
}
doSomething("1st Call")
.then(function() {
doSomething("2nd Call");
console.log('leaving 2nd promise');
})
.then(function() {
doSomething("3rd Call");
console.log('leaving 3rd promise');
});
输出到控制台
- '第一次通话'
- 'In the promise'
- 'leaving 2nd promise'
- 'leaving 3rd promise'
- '第二次通话'
- 'In the promise'
- '第三次通话'
- 'In the promise'
主要问题
为什么 JavaScript 似乎没有在 promise 中按顺序读取代码行?它几乎看起来像是先进行传递,然后先进行控制台日志记录,然后返回代码并执行承诺在 .then 方法之后执行的功能。任何见解将不胜感激...
doSomething("2nd Call");
console.log('leaving 2nd promise');
Do something 是异步的,需要 ~1000
m/s 才能完成执行。因此,当 doSomething("2nd Call");
最初被调用时,您的代码跳转到您的方法,returns 承诺,并开始 setTimeout
。然后,记录 "leaving 2nd promise"
。稍后沿着轨道,我们之前通过调用 doSomething("2nd Call")
启动的 setTimeout 将完成,因此它将 "2nd Call"
记录到控制台。要等待对 doSomething("2nd Call")
的初始调用完成,您需要使用 .then()
(或 await
)来承诺它 returns,这样您就可以在承诺解决:
function doSomething(msg) {
return new Promise(
(myresolve, myreject) => {
setTimeout(
() => {
console.log(msg);
console.log('In the promise')
myresolve();
},
1000);
});
}
doSomething("1st Call")
.then(() => doSomething("2nd Call"))
.then(() => console.log('leaving 2nd promise'))
.then(() => doSomething("3rd Call"))
.then(() => console.log('leaving 3rd promise'));
所以我正在使用 promise 做一些工作,当我在 promise 中使用 console.log() 时出现了一些奇怪的行为。
代码
function doSomething(msg){
return new Promise(
(myresolve, myreject) => {
setTimeout(
() => {
console.log(msg);
console.log('In the promise')
myresolve();
},
1000);
});
}
doSomething("1st Call")
.then(function() {
doSomething("2nd Call");
console.log('leaving 2nd promise');
})
.then(function() {
doSomething("3rd Call");
console.log('leaving 3rd promise');
});
输出到控制台
- '第一次通话'
- 'In the promise'
- 'leaving 2nd promise'
- 'leaving 3rd promise'
- '第二次通话'
- 'In the promise'
- '第三次通话'
- 'In the promise'
主要问题 为什么 JavaScript 似乎没有在 promise 中按顺序读取代码行?它几乎看起来像是先进行传递,然后先进行控制台日志记录,然后返回代码并执行承诺在 .then 方法之后执行的功能。任何见解将不胜感激...
doSomething("2nd Call");
console.log('leaving 2nd promise');
Do something 是异步的,需要 ~1000
m/s 才能完成执行。因此,当 doSomething("2nd Call");
最初被调用时,您的代码跳转到您的方法,returns 承诺,并开始 setTimeout
。然后,记录 "leaving 2nd promise"
。稍后沿着轨道,我们之前通过调用 doSomething("2nd Call")
启动的 setTimeout 将完成,因此它将 "2nd Call"
记录到控制台。要等待对 doSomething("2nd Call")
的初始调用完成,您需要使用 .then()
(或 await
)来承诺它 returns,这样您就可以在承诺解决:
function doSomething(msg) {
return new Promise(
(myresolve, myreject) => {
setTimeout(
() => {
console.log(msg);
console.log('In the promise')
myresolve();
},
1000);
});
}
doSomething("1st Call")
.then(() => doSomething("2nd Call"))
.then(() => console.log('leaving 2nd promise'))
.then(() => doSomething("3rd Call"))
.then(() => console.log('leaving 3rd promise'));