多个POST请求的异步问题

时间:2017-08-08 08:52:17

标签: javascript node.js asynchronous settimeout

我使用函数_getLogFileUrls执行POST请求并将数据返回给回调函数。返回的数据正被添加到数组中。

在循环中调用函数_getLogFileUrls

如何在完成所有请求后返回结果数组?

我理解setTimeout对于这种方法是错误的方式,我编写代码的方式是创建一个回调地狱。如何在不涉及各种异步问题的情况下摆脱setTimeout函数。

// app.post('/api/getLogs', auth, loggingAPI.getLogs); // Make API request

function getLogs(req, res) {
    if ( ! req.body.id) {
        return res.status(500).send('Please check the params!');
    }

    var date;

    if (req.body.date) {
        date = req.body.date;
    } else {
        date = new Date().toISOString().slice(0,10);
    }

    var sqlQuery = "SELECT `LogFileID` FROM `logs_data` WHERE `EmpID` = '" + req.body.id + "' AND DATE(`Timestamp`) = '" + date + "'",
        resArray= [];

    hitThisQueryForMe(sqlQuery, res, function(rows) {
        if ( ! rows.length) res.json(rows);

        _.each(rows, function(item) {
            console.log('item: ' + item.LogFileID);
            _getLogFileUrls(item.LogFileID, function(response) {
                resArray.push(response);
            });
        });

        setTimeout(function() {
            console.log('final urls: ' + JSON.stringify(resArray));   
            res.send(resArray);
            resArray = [];
        }, 4000);

    });
}

function _getLogFileUrls(logFileId, callback) {
  var request = require('request'),
    config = require('../../config.js');    

    var fileParams = {
        fileName: 'LogFiles/' + logFileId       
    };

    request.post({
        url: config.filesServiceUrl + 'get-logfile-urls',
        json: fileParams
    }, function(error, response, body) {
        if (!error && response.statusCode === 200) {
            callback(body);
        } else {
            console.log('err requesting  logs: ' + JSON.stringify(error));
            res.status(400).send('Err requesting  logs:');
        }
    }).on('error', function(err) {
        console.log('File service error for Logs: ' + err);
    });
}

1 个答案:

答案 0 :(得分:2)

使用async.eachOf迭代数组并对每个元素应用异步函数:

async.eachOf(myArray, function(myElementInArray, it, callback){

    // call async function on element
    myAsyncFunction(myElementInArray, function(err){
       if(err)
         return callback(err); // abort async flow
       else
         return callback(); 
    });

}, function(err){
  // final callback called when the flow is finished

});

////编辑

异步模块文档:https://caolan.github.io/async/docs.html

替换此代码:

        _.each(rows, function(item){            
            console.log('item: ' + item.LogFileID);
            _getLogFileUrls(item.LogFileID, function(response){
                resArray.push(response);            
            });         
        });

        setTimeout(function(){
            console.log('final urls: ' + JSON.stringify(resArray)); 
            res.send(resArray);
            resArray = [];
        }, 4000);

 var async = require("async");
 var resArray = [];
 async.eachOf(rows, function(item, it, callback){

    console.log('item: ' + item.LogFileID);
    // call async function on element
     _getLogFileUrls(item.LogFileID, function(response){
         resArray.push(response);
         return callback(); 
    });

}, function(err){
  // final callback called when the flow is finished
   console.log('final urls: ' + JSON.stringify(resArray)); 
   res.send(resArray);
});