javascript - NodeJs:HTTP请求的多个循环同时执行
问题描述
根据上述问题,回答了如何使用一组 url 执行 http 请求的循环,它工作正常。但我想要实现的是执行另一个 http 请求循环,这应该只在完成后完成第一个循环(即)它应该等待 http 请求的第一个循环完成。
// Import http
var http = require('http');
// First URLs array
var urls_first = ["http://www.google.com", "http://www.example.com"];
// Second URLs array
var urls_second = ["http://www.yahoo.com", "http://www.fb.com"];
var responses = [];
var completed_requests = 0;
function performHTTP(array) {
for (i in urls_first) {
http.get(urls[i], function(res) {
responses.push(res);
completed_requests++;
if (completed_requests == urls.length) {
// All download done, process responses array
console.log(responses);
}
});
}
}
在上面的代码片段中,我添加了另一个 url 数组。我将 for 包装在一个函数中,以在每次调用时更改数组。因为我必须等待第一个循环完成,所以我尝试了 async/await,如下所示。
async function callMethod() {
await new Promise (resolve =>performHTTP(urls_first))) // Executing function with first array
await new Promise (resolve =>performHTTP(urls_second))) // Executing function with second array
}
但是在这种情况下,两个函数调用同时执行(即)它不等待第一个数组执行完成。两个执行同时发生,我只需要在完成一个之后发生。
解决方案
您需要在 Promise 中提出您的请求:
function request(url) {
return new Promise((resolve, reject) => {
http.get(url, function(res) {
// ... your code here ... //
// when your work is done, call resolve to make your promise done
resolve()
});
}
}
然后解决您的所有请求
// Batch all your firts request in parallel and wainting for all
await Promise.all(urls_first.map(url => request(url)));
// Do the same this second url
await Promise.all(urls_second.map(url => request(url)));
请注意,此代码未经测试,可能包含一些错误,但主要原理在这里。
有关 Promise 的更多信息:https ://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Promise
推荐阅读
- node.js - Node.js 使用 find 和 head 读取大文件目录
- python - 无法在 Python 中读取环境变量
- c - JSON解析器使用c
- vue.js - 如何动态设置 Veutify 的对话框组件“持久”属性
- ios - MKMapView 随机崩溃 - VKMapCameraController
- java - 如何使用占位符'?在 LIKE 运算符中?
- java - 如何转换 LinkedHashMap
> 变成一个 JSONObject? - json - 将两个 json 数组(加载到内存中)合并为一个 json 数组
- json - 这种类似 JSON 的数据格式是什么(由换行符分隔)?
- php - 使用无法正常工作的会话从数据库中获取数据