【问题标题】:NodeJs facing the issue while using async waterfallNodeJs 在使用异步瀑布时面临问题
【发布时间】:2019-10-17 19:07:41
【问题描述】:

我一个接一个地调用 2 个 API 请求 1,所以我决定使用瀑布模型,但我遇到了这个问题

我尝试了很多,但无法解决问题。

下面是我的代码:

var unirest = require("unirest");
var async = require("async")

exports.user = (req, res, next) => {
    const qry = req.params.id
    async.waterfall([
        (nextCall) => {
            var req = unirest("GET", API_URL1);
            req.query({
               // some query
            });
            req.headers({
               // some headers 
            });
            req.end(function(subCount) {
                // if (resp.error) throw new Error(resp.error);
                var channelSubCount = subCount.body
                nextCall(null, data)
            });
        },
        (data, nextCall => {
            console.log(channelSubCount, 'data')
            var reqs = unirest("GET", API_URL2);

            reqs.query({
              // some query
            });

            reqs.headers({
                // some headers
            });

            reqs.end(function(res) {
                // if (res.error) throw new Error(res.error);
                console.log(res.body);
                return nextCall(null, {
                    name: 'abc',
                    photo: 'src',
                    count: data
                })
            });
        })
    ], function(finalData) {
        // if (error) { alert('Something is wrong!'); }
        console.log('final')
        res.status(200).json(
            finalData
        );
    });
};

错误: 引用错误:数据未定义

我不明白为什么会这样。

还有一些请告诉我通过优化实现上述内容的正确方法。

任何帮助表示赞赏...

【问题讨论】:

    标签: javascript node.js asynchronous ecmascript-6 async.js


    【解决方案1】:

    看起来您忘记在第二个箭头函数定义中关闭括号了:

    (data, nextCall => {
    

    它仍然是一个有效的 JavaScript,但解释器现在将 data 不作为函数传入参数(根据您的需要),而是作为一个变量。但它没有在任何地方定义,因此你有这个错误。

    这样就可以了:

    (data, nextCall) => {
    

    【讨论】:

      猜你喜欢
      • 2020-09-06
      • 2014-10-09
      • 1970-01-01
      • 2014-10-31
      • 2018-04-29
      • 2015-09-03
      • 1970-01-01
      • 2016-01-20
      相关资源
      最近更新 更多