如何使用Node Js Promise顺序执行函数?

时间:2017-02-14 23:39:48

标签: javascript node.js promise es6-promise

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

(function() {

    var module = angular.module("missingDog");

    var MascotaService = function($resource) {
        return $resource("rest/mascotas/:args", {args: "@args"}, {
            query: {
                method: 'GET',
                cache: false,
                isArray: true
            }
        });
    };

    module.factory("MascotaService", MascotaService);

}());

我想要的输出是

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

我遗失了一些东西,但我无法弄明白请解释我

1 个答案:

答案 0 :(得分:2)

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

下面是一个工作片段:



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)
    });
}