异步从循环发送多个请求

时间:2018-12-20 12:12:04

标签: node.js

我正在开发一个必须读取excel文件并将每一行发送到服务器的应用程序;

现在,我想异步进行此操作,我想在发送另一个请求server.postRequest(1);之前获取server.postRequest(2);的结果

for (let row = 2; row <= nrows; row++) {
    Excel.mapExcelLine(workbook.Sheets[firstSheetName], row, ncols)
    .then((data) => {
        let idExcel = data.id;
        database.get("SELECT * FROM sync WHERE idExcel=?", [idExcel], async function (err, row) {
            if (row == undefined) {
                let promise = await server.postRequest(row.id);
            }
        }
    });
}

这里是postRequest函数

postRequest(id){
    return new Promise(function (resolve, reject) {
        options.body = id;
        request.post(options, function (error, response, body) {
            if (response.headers['msg'] == 'authrequired') {
                 request.post(authOptions, function (error, response, body) {
                       if(response.headers['msg'] == 'ok')
                           postRequest(id);
                       else resolve(402);
                 });
            }
            else if(response.headers['msg'] == 'ok'){
                 logger.info('Demand' + id + 'created'
                 resolve(200);    
            }
        });
    });
}

现在,当我尝试遍历此数组时,例如:

[1,2,3,4]
postResquest函数中的

消息显示顺序不正确。

如何在发送另一个请求之前等待每个请求完成?

预期输出为:

Demand 1 created
Demand 2 created
Demand 3 created
Demand 4 created

1 个答案:

答案 0 :(得分:0)

对于异步发送的请求,必须使用await