Javascript Promises 显式函数与内联函数

标签 javascript node.js es6-promise

我试图了解 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/

相关文章:

javascript - 动态打印两个不同字符串中的替代字符串字符

javascript - 返回函数 JavaScript

node.js - 使用 promisify 时找不到属性 'svc'

javascript - 将带有回调和其他参数的函数传递给另一个函数

javascript - 返回多个值,包括 promise

javascript - 查找与搜索框匹配的链接

javascript - 有没有办法在不使用事件监听器的情况下从文本/事件流中获取单个响应?

javascript - 在图像预览中选择“可拖动”

json - 使用反斜杠解析 JSON Node.js

node.js - 如何在 Node.JS 中不建立缓冲区的情况下通过管道传输文件?