我试图了解 javascript promises 的古怪世界,但遇到了这个我不明白的问题。
第一个程序来自一本解释 promise 链的书,它的工作原理与您想象的一样:
var Promise = require('promise');
function delay(time) {
return new Promise( function(resolve,reject) {
setTimeout( resolve, time );
});
}
delay(1000) // step 1
.then(function STEP2(){
console.log( "step 2b (after 1000ms)" );
return delay( 2000 );
})
.then(function STEP3(){
console.log( "step 3b (after another 2000ms)" );
})
.then(function STEP4(){
console.log( "step 4b (next Job)" );
return delay( 5000 );
})
.then(function STEP5() {
console.log( "step 5b (after another 5000ms)" );
});
控制台日志在正确的延迟后出现。
现在,为了让我自己更清楚这一点,我明确地制作了 STEP 函数,所以程序现在看起来像这样:
var Promise = require('promise');
function delay(time) {
return new Promise( function(resolve,reject){
setTimeout( resolve, time );
});
}
function STEP2() {
console.log( "step 2 (after 1000ms)" );
return delay( 2000 );
}
function STEP3() {
console.log( "step 3 (after another 2000ms)" );
}
function STEP4() {
console.log( "step 4 (next Job)" );
return delay( 5000 );
}
function STEP5() {
console.log( "step 5 (after another 5000ms)" );
}
delay( 1000 ).then(STEP2()).then(STEP3()).then(STEP4()).then(STEP5());
但是现在所有控制台日志同时发生,程序延迟 5000 毫秒然后退出。有人可以解释上面两个例子之间有什么不同(功能上)吗?谢谢。
最佳答案
在您的第一个示例中,您传递了一个函数。在您的第二个示例中,您将传递函数的结果,因为您在函数名称之后包含了 ()
。
这可能是您想要做的:
delay( 1000 ).then(STEP2).then(STEP3).then(STEP4).then(STEP5);
关于Javascript Promises 显式函数与内联函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32749541/