Javascript承诺显式函数与内联函数

kev*_*dev 2 javascript node.js es6-promise

我正在努力理解javascript承诺的糟糕世界,并且遇到了我不明白的事情.

第一个程序来自一本书,解释了承诺链,并按照您的想法工作:

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)" );
    });
Run Code Online (Sandbox Code Playgroud)

在正确的延迟量之后出现控制台日志.

现在,为了让我更清楚,我明确地制作了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());
Run Code Online (Sandbox Code Playgroud)

但现在所有控制台日志都会立即发生,程序会延迟5000毫秒然后退出.有人可以解释上面两个例子之间的不同(功能上)吗?谢谢.

Ani*_*sur 6

在您的第一个示例中,您正在传递一个函数.在第二个示例中,您传递了函数的结果,因为您包含()了函数名称之后.

这可能是你想要做的:

delay( 1000 ).then(STEP2).then(STEP3).then(STEP4).then(STEP5);
Run Code Online (Sandbox Code Playgroud)

  • @kevdev - 您必须传递一个函数引用,以便promise基础结构可以稍后调用它.`function(){console.log("After 2000ms")}`是一个函数引用.`console.log("2000ms以后")`不是函数引用.它立即运行`console.log()`并传递返回结果,执行它是'undefined`. (2认同)

归档时间:

查看次数:

1192 次

最近记录:

10 年,2 月 前