gpt4 book ai didi

javascript - 多个 POST 请求的异步问题

转载 作者:行者123 更新时间:2023-12-01 03:15:21 26 4
gpt4 key购买 nike

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

函数_getLogFileUrls在循环中调用。

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

我知道 setTimeout 对于这种方法来说是错误的方式,并且我编写代码的方式正在创建回调 hell 。如何摆脱 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);
});
}

最佳答案

使用 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);
});

关于javascript - 多个 POST 请求的异步问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45563722/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com