【问题标题】:How to pass value between Async.series functions without global variable如何在没有全局变量的 Async.series 函数之间传递值
【发布时间】:2017-10-23 11:46:01
【问题描述】:
var Async = require('async');

var Test_Hander = function () {
};

Test_Hander.prototype.begin = function () {
    Async.series([
        this.first, // this.first.bind(this) does not work either
        this.second
    ],function (error) {
        if (error) {
            // shit
        }
        else {
            // good
        }
    });

};

Test_Hander.prototype.first = function (callback) {
    console.log('Enter first function');
    callback(null,'I am from first function');
};

Test_Hander.prototype.second = function (one, callback) {
    console.log('Enter second function');
    console.log('parameter one: ');
    console.log(one);
    console.log(callback);

    callback(null);
};

var hander = new Test_Hander();
hander.begin();

我想将一些值从第一个函数传递给第二个函数。而且我知道瀑布和全局变量都可以。但是,我可以不使用瀑布和全局变量将结果值从第一个函数传递给第二个函数吗?

【问题讨论】:

  • 我也遇到过类似的情况,如果不添加全局变量,我还没有找到解决方案。链接到重复的问题https://stackoverflow.com/questions/22424592/nodejs-async-series-pass-arguments-to-next-callback/22424905 当使用 Promise 可以实现这一点时,为什么你觉得需要使用 Async 库。
  • 是因为历史代码
  • Ahh I c.. 然后按照重复问题中接受的答案并通过声明变量来使其工作。
  • @Vish 从您的链接答案中,是的,我知道它有效,但如果我们有很多功能,该解决方案可能不好。
  • 如果要求是与从第一个到第二个传递的参数串联执行函数,那么声明全局变量有什么顾虑?这是我之前关于同一问题的讨论的链接。 https://stackoverflow.com/questions/14305843/how-do-i-pass-a-standard-set-of-parameters-to-each-function-in-an-async-js-serie/14306023#comment74056947_14306023

标签: node.js async.js


【解决方案1】:

使用 Promise,您可以链接方法并执行类似于 async.series 的代码,并且您不需要 async 模块。

var Test_Hander = function () {
};

Test_Hander.prototype.begin = function () {
    this.first()
        .then(this.second)
        .catch(function(err){
            // Handle error
        });

};

Test_Hander.prototype.first = function (callback) {
    return new Promise(function(reject, resolve){
        // do something
        // if err : reject(err)
        // else : resolve(data);
    });
};

Test_Hander.prototype.second = function (responsefromFirst) {
    // Do somethign with response
};

var hander = new Test_Hander();
hander.begin();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多