Node.js的async.series是如何它应该工作? [英] node.js async.series is that how it is supposed to work?

查看:140
本文介绍了Node.js的async.series是如何它应该工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var async = require('async');

function callbackhandler(err, results) {
    console.log('It came back with this ' + results);
}   

function takes5Seconds(callback) {
    console.log('Starting 5 second task');
    setTimeout( function() { 
        console.log('Just finshed 5 seconds');
        callback(null, 'five');
    }, 5000);
}   

function takes2Seconds(callback) {
    console.log('Starting 2 second task');
    setTimeout( function() { 
        console.log('Just finshed 2 seconds');
        callback(null, 'two');
    }, 2000); 
}   

async.series([takes2Seconds(callbackhandler), 
              takes5Seconds(callbackhandler)], function(err, results){
    console.log('Result of the whole run is ' + results);
}) 

输出类似于如下:

The output looks like below :

Starting 2 second task
Starting 5 second task
Just finshed 2 seconds
It came back with this two
Just finshed 5 seconds
It came back with this five

我期待takes2Second功能takes5Second开始之前完全完成。
是,它是如何工作的。请告诉我。
而最终的函数不运行。谢谢。

I was expecting the takes2Second function to finish completely before the takes5Second starts. Is that how it is supposed to work. Please let me know. And the final function never runs. Thanks.

推荐答案

不太。你正在(只要数组的求)立即执行的功能,这就是为什么它们出现在同一时间开始

Not quite. You are executing the functions immediately (as soon as the array is evaluated), which is why they appear to start at the same time.

传递给每个将要执行的功能的回调是内部的异步库。您可以执行一次你的函数完成,传递错误和/或值。你并不需要自己定义的功能。

The callback passed to each of the functions to be executed is internal to the async library. You execute it once your function has completed, passing an error and/or a value. You don't need to define that function yourself.

最后一个函数永远不会在你的情况下运行,因为异步需要你调用回调函数,在移动到下一个功能,该系列中从未真正被执行(仅适用于你的的callbackHandler 函数被执行)。

The final function never runs in your case because the callback function that async needs you to invoke to move on to the next function in the series never actually gets executed (only your callbackHandler function gets executed).

试试这个:

async.series([
    takes2Seconds,
    takes5seconds
], function (err, results) {
    // Here, results is an array of the value from each function
    console.log(results); // outputs: ['two', 'five']
});

这篇关于Node.js的async.series是如何它应该工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆