NodeJS灵活模块系列功能不起作用

时间:2014-06-14 10:37:07

标签: javascript node.js flow-control

这段代码有什么问题,它应该运行所有3个函数,但它只运行第一个:

var flow = require('nimble');
function first() {
    setTimeout(function () {
        console.log('First');
    }, 500);
}

function second() {
    setTimeout(function () {
        console.log('Second');
    }, 500);
}

function last() {
    setTimeout(function () {
        console.log('Last');
    }, 500);
}

flow.series([first, second, last]);

2 个答案:

答案 0 :(得分:1)

Nimble要求每个函数在系列中运行以调用回调函数,该函数告诉Nimble继续执行系列中的下一个任务。示例就在Nimble homepage上。

这是您的代码的更新版本。

var flow = require('nimble');
function first(callback) {
  setTimeout(function() {
    console.log('First');

    callback();
  }, 500);
}

function second(callback) {
  setTimeout(function() {
    console.log('Second');

    callback();
  }, 500);
}

function last(callback) {
  setTimeout(function() {
    console.log('Last');

    callback();
  }, 500);
}

flow.series([first, second, last]);

答案 1 :(得分:1)

Nimble接受串联或parrallal的回调函数,但你需要在数组中给它们。

// first we need to install nimble with 'npm install nimble'
//there is a another flow control tool called nimble
//we need to add it using require.is small codebase

var flow = require('nimble');

//in nimble we will pass each set of function as a element of array
//hence we are including them in [] 

flow.series([
    function(callback){
        setTimeout(function(){
            console.log('I execute first');
            callback();
        },1000);
    },
    function(callback){
        setTimeout(function(){
            console.log('I execute second');
            callback();
        },2000);
    },
    function(callback){
        setTimeout(function(){
            console.log('I execute third');
            callback();
        },3000);
    },
]);

我认为它会帮助你更多地理解