【问题标题】:How to execute functions sequentially using Node Js Promise?如何使用 Node Js Promise 顺序执行函数?
【发布时间】:2017-02-15 08:13:46
【问题描述】:

我是 Node js Promise 的新手,我不确定我是否正确使用了 Promise,所以这是我的代码。

function print(){

    first('first')
    .then(second('second'))
    .then(third('third'));
}

function first(a){
    return new Promise((resolve, reject) => {
        var res1 = function (){
            resolve(a);
        }    
    });
    console.log(a);
}

function second(b){
    return new Promise((resolve, reject) => {
        var res1 = function (){
            resolve(b);
        }    
    });
    setTimeout(() => {
        console.log(b);
    }, 2000);
}

function third(c){
    return new Promise((resolve, reject) => {
        var res1 = function (){
            resolve(c);
        }    
    });
    console.log(c);
}

我想要的输出是

first
second
third

我得到的是

first
third
//after two seconds
second

我遗漏了一些东西,但我无法弄清楚,请解释一下

【问题讨论】:

  • 然后期望一个函数作为它的参数——而不是运行函数的结果!
  • 您的代码不会产生任何输出 - 每个函数在语法上都是错误的,并且在第一个、第二个和第三个中都有无法访问的代码 - 并且第一个、第二个或第三个都不会解决... 更多代码中的错误大于正确

标签: javascript node.js promise es6-promise


【解决方案1】:

要获得预期的行为,您需要在超时内(控制台日志旁边)resolve。您也不能将参数传递给 Promise 链函数,因为它们需要接受来自前一个 thennable 的 Promise。

一个工作的sn-p如下:

print();

function print(){
    first('first')
    .then(second)
    .then(third);
}

function first(a){
    return new Promise((resolve, reject) => {
    		console.log(a);
        resolve(a);  
    });
}

function second(b){
    return new Promise((resolve, reject) => {
      setTimeout(() => {
      		console.log("second");
      		resolve(b);
      }, 2000);  
    });

}

function third(c){
    return new Promise((resolve, reject) => {
    		console.log("third"); 
        resolve(c)
    });
}

【讨论】:

    猜你喜欢
    • 2020-08-22
    • 1970-01-01
    • 2016-08-24
    • 1970-01-01
    • 2016-04-07
    • 2020-08-20
    • 2023-03-16
    • 1970-01-01
    • 2020-04-13
    相关资源
    最近更新 更多