gpt4 book ai didi

javascript - node.js:如何在 forEach 循环中使用异步调用实现路由方法?

转载 作者:搜寻专家 更新时间:2023-11-01 00:17:48 24 4
gpt4 key购买 nike

我必须实现这样的逻辑:

var express = require('express'),
request = require('request');

var array = [
{ url: 'http://www.example1.com' },
{ url: 'http://www.example2.com' },
];

express.Router().get('/job', function (req, res) {
results = [];
array.forEach(function (item) {
request(item.url, function (error, response, body) {
if (!error && response.statusCode == 200) {
results.push(body);
}
});
res.json(results); // <== wrong, results array is empty, here...
});

如何调用 res.json(results) 确保 forEach 循环结束?

更新:它不是建议答案的重复!

我需要在所有请求完成时执行 res.json(),而在 forEach 循环完成时不需要...:-(

最佳答案

实现此目的的简单方法:

var express = require('express'),
request = require('request');

var array = [
{ url: 'http://www.example1.com' },
{ url: 'http://www.example2.com' },
];

//store number of completed calls
var completed = 0;

express.Router().get('/job', function (req, res) {
results = [];
array.forEach(function (item) {
request(item.url, function (error, response, body) {
if (!error && response.statusCode == 200) {
results.push(body);

completed = completed + 1; //iterate counter
onComplete(); //attempt completion
}
});

function onComplete(){
if(completed != array.length) {
return;
}
res.json(results);
// ... rest of code that relies on results
};

});

关于javascript - node.js:如何在 forEach 循环中使用异步调用实现路由方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32590761/

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