Nodejs是同步执行的最佳方式吗?

时间:2018-02-13 15:37:29

标签: javascript node.js bluebird q async.js

使用外部模块时,同步执行的最佳方法是什么?我想输出结果:

Setp 1: Hello
Setp 2: Hej 
Step 3: Hola  
Step 4: Bonjour

示例:

//File: main.js
var greetings = require("./greetings.js");

console.log(greetings.sayHelloInEnglish());
console.log(greetings.sayHelloInSwedish());
console.log(greetings.sayHelloInSpanish());
console.log(greetings.sayHelloInFrench());

//File: greetings.js
module.exports = {
    sayHelloInEnglish: function() {
        return "Step 1: Hello"
    },
    sayHelloInSpanish: function() {

        setTimeout(function (){return "Step 3: Hola"},4000);
    },
    sayHelloInFrench: function() {
        return "Step 4: Bonjour";
    },
    sayHelloInSwedish: function() {
        setTimeout(function (){return "Step 2: Hej"},8000);
    }
};

2 个答案:

答案 0 :(得分:0)

感谢Malice建议您使用异步。但知道是否有实施仍然很有意思?

" setTimeout"是象征数据库请求或其他一些延迟操作。

//File: main.js

var greetings = require("./greetings.js");
var async =  require('async');
async.waterfall([
        function firstStep(done) {
            greetings.sayHelloInEnglish(done);


        },
        function secondStep(step1Result, done) {
            console.log(step1Result);

            greetings.sayHelloInSwedish(done);


            //done(null, 'Value from step 2'); // <- set value to passed to step 3
        },
        function thirdStep (step2Result, done) {
            console.log(step2Result);

            greetings.sayHelloInSpanish(done);

            //done(null, 'Value from step 3'); // <- no value set for the next step.
        },
        function fourthStep (step3Result, done) {
            console.log(step3Result);

            greetings.sayHelloInFrench(done);
            //done(null, 'Value from step 4');
        },
        function fifthStep (step4Result, done) {
            console.log(step4Result);

            greetings.sayHelloInFrench(done);

        }


    ],
    function (err) {
        if (err) {
            throw new Error(err);
        } else {
            console.log('No error happened in any steps, operation done!');
        }
    });

//File: greetings.js

module.exports = {

    sayHelloInEnglish: function(callback) {
        callback(null,"Setp 1: HELLO");

    },

    sayHelloInSpanish: function(callback) {

        setTimeout(function (){callback(null,"Step 3: Hola")},8000);

    },

    sayHelloInFrench: function(callback) {
        callback(null, "Step 4: Bonjour");
    },

    sayHelloInSwedish: function(callback) {

        setTimeout(function (){callback(null,"Setp 2: hej!!")},8000);
    }

};

答案 1 :(得分:0)

如果您有许多需要按顺序运行的承诺生成函数,您可以手动执行:

var greetings = require(&#34; ./ greetings.js&#34;);

// File: greetings.js
module.exports = {
    sayHelloInEnglish: function() {
        return Promise.resolve("Step 1: Hello");
    },

    sayHelloInSpanish: function() {
        return Promise.resolve("Step 3: Hola");
    },

    sayHelloInFrench: function() {
        return Promise.resolve("Step 4: Bonjour");
    },

    sayHelloInSwedish: function() {
        return Promise.resolve("Step 2: Hej");
    }
};

// File: main.js
greetings.sayHelloInEnglish()
   .then(() => greetings.sayHelloInSwedish())
   .then(() => greetings.sayHelloInSpanish())
   .then(() => greetings.sayHelloInFrench());

或者

// File: main.js
greetings.sayHelloInEnglish()
   .then(greetings.sayHelloInSwedish)
   .then(greetings.sayHelloInSpanish)
   .then(greetings.sayHelloInFrench);

如果你想运行动态构造的函数序列,你需要这样的东西:

// File: greetings.js
const functions = [greetings.sayHelloInEnglish, greetings.sayHelloInSwedish, greetings.sayHelloInSpanish, greetings.sayHelloInFrench];

const firstFunction = functions.splice(0, 1)[0];
const result = Promise.resolve(firstFunction());

functions .forEach((current) => {
    result = result.then(current);
});

return result;

有更紧凑的方法来实现这一目标。一旦你知道它是如何工作的,你就可以改进它。