如何使用async.series来等待响应

How to use async.series to wait for response?

本文关键字:等待 响应 series 何使用 async      更新时间:2023-09-26

我昨天发布了这个问题:https://stackoverflow.com/questions/25919099/how-do-i-use-callback-to-solve-authentication-issue

基本上,我想等待登录请求的响应,然后转到签入请求。否则,签入请求给出401,这是身份验证错误。

现在我正在尝试使用一些库,如step、wait.fo或async来等待响应。使用async.series,我正在尝试此代码,但它在function two() 处出现unexpected token function错误

function checkin() {
    async.series[(
                function one() {
                    agent1
                        .post(login-url)
                        .type('form') // send request in form format
                        .send({
                            username: username,
                            password: password
                        })
                        .end(function(err, res) {
                            console.log("response for login is ", res.statusCode, " ", res.message);
                        });
                }
                function two() {
                    for (var i = 0; i < count; i++) {
                        if (validatePayment(rows[i].Payment) == true && validateMobile(rows[i].Mobile) == true) {
                            console.log("inside validation");
                            agent1
                                .post(checkin-url)
                                .send({
                                    phone: rows[0].Mobile,
                                    outlet: outletID
                                        //outlet: "rishi84902bc583c21000004"
                                })
                                .end(function(err, res) {
                                    console.log("response for checkins is ", res.statusCode, " ", res.message);
                                });
                        )];
                }
            }
        }
        //    });
}

由于试图在带括号的表达式中定义多个函数,因此会出现意外的标记错误。在你的控制台上试试这句话:

(function one() {} function two() {})

这里发生的事情是,你试图访问async.series,就像它是一个数组或其他什么:

async.series[ ...index here... ]

然后,对于索引,您传递一个表达式:

async.series[ (...) ];

该表达式错误地包含两个函数定义:

async.series[ ( function one() { ... } function two() { ... } ) ]

带括号的表达式应该只返回一个值。两个函数将竞争成为该返回值,因此无效。但你所做的一切都是错误的。

我认为你真正的意思是调用async.series,并传递functionsarray。。。

async.series( [ function one() {...}, function two() {...} ] );

您更新的代码可能看起来像这个小提琴。