Javascript promises给了我一些意想不到的行为,当他们使用断点进行调试时,它们以同步和预期的方式输出,但是在运行时似乎做了一些奇怪的和异步的行为。这是我的代码:
function aPromise() {
return new Promise(function(resolve, reject) {
console.log("making a promise")
bPromise().then(function() {
console.log("resolving a promise")
resolve();
});
});
}
function bPromise() {
return new Promise(function(resolve, reject) {
console.log("making b promise")
console.log("resolving b promise")
resolve();
});
}
function logDone() {
console.log("done");
}
aPromise().then(logDone)
aPromise().then(logDone)
上述控制台的输出是:
making a promise
making b promise
resolving b promise
making a promise
making b promise
resolving b promise
resolving a promise(2)
done(2)
我觉得很奇怪。奇怪的是,当我设置一个断点并逐行换行时,输出就是我所期望的:
making a promise
making b promise
resolving b promise
resolving a promise
done
making a promise
making b promise
resolving b promise
resolving a promise
done
为什么会发生这种情况,我该如何解决?
我正在运行最新的Firefox 45.0.1。它似乎也发生在Chrome中。