使用 setTimeout 的基本 JavaScript 承诺测试
Basic JavaScript promise test with setTimeout
我正在尝试使用 bluebird 进行基本的承诺测试,但结果不是我所期望的。我试图让 "Should I be logged first? 4000" 消息先登录到我的控制台,但第二条控制台消息总是首先显示。我做错了什么,我需要做什么才能在 2000 条消息之前记录“4000”消息?
function longRunningPositiveTest3() {
return new Promise(function(resolve) {
setTimeout(function () {
console.log("Should I be logged first? 4000");
resolve();
}, 4000);
});
}
function longRunningPositiveTest4() {
return new Promise(function(resolve) {
setTimeout(function () {
console.log("Should I be logged first? 2000");
resolve();
}, 2000);
});
}
Promise.resolve(longRunningPositiveTest3())
.then(longRunningPositiveTest4());
谢谢
您正在调用两个立即启动超时的函数。您需要将回调函数传递给 then
!
使用
Promise.resolve(…) // some starting promise
.then(longRunningPositiveTest3)
.then(longRunningPositiveTest4);
或
longRunningPositiveTest3() // no need to wrap it in Promise.resolve() (but no harm either)
.then(longRunningPositiveTest4);
我正在尝试使用 bluebird 进行基本的承诺测试,但结果不是我所期望的。我试图让 "Should I be logged first? 4000" 消息先登录到我的控制台,但第二条控制台消息总是首先显示。我做错了什么,我需要做什么才能在 2000 条消息之前记录“4000”消息?
function longRunningPositiveTest3() {
return new Promise(function(resolve) {
setTimeout(function () {
console.log("Should I be logged first? 4000");
resolve();
}, 4000);
});
}
function longRunningPositiveTest4() {
return new Promise(function(resolve) {
setTimeout(function () {
console.log("Should I be logged first? 2000");
resolve();
}, 2000);
});
}
Promise.resolve(longRunningPositiveTest3())
.then(longRunningPositiveTest4());
谢谢
您正在调用两个立即启动超时的函数。您需要将回调函数传递给 then
!
使用
Promise.resolve(…) // some starting promise
.then(longRunningPositiveTest3)
.then(longRunningPositiveTest4);
或
longRunningPositiveTest3() // no need to wrap it in Promise.resolve() (but no harm either)
.then(longRunningPositiveTest4);