【发布时间】:2021-05-20 17:00:08
【问题描述】:
我有一个方法askGoogle 模拟发送http 请求。我在 for 循环中调用 askGoogle 10 次。每个askGoogle 调用都需要随机的时间来执行。
这 10 个请求是异步发送的,这意味着第二个请求不会等到第一个请求完成后再发送,依此类推。因此,有时第一个请求需要更长的时间才能完成,这会导致第四个或第 8 个请求提前执行。
我希望在所有请求完成后打印一条消息Done!。
我试图做到这一点,但我所有的尝试都失败了。
const https = require("https");
function askGoogle(i) {
setTimeout(() => {
const googleRequest = https.request("https://google.com", {
method: "GET"
});
googleRequest.once("error", err => {
console.log("Something happened!");
})
googleRequest.once("response", (stream) => {
stream.on("data", x => {
});
stream.on("end", () => {
console.log("Done with google " + i);
i++;
})
})
googleRequest.end();
}, getRandomInt(0, 5_000));
}
function findSolution() {
for (let j = 0; j < 10; j++) {
askGoogle(j);
}
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
let randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
return randomNumber;
}
findSolution();
console.log("Done!");
输出:
Done!
Done with google 7
Done with google 0
Done with google 4
Done with google 1
Done with google 8
Done with google 9
Done with google 6
Done with google 2
Done with google 3
Done with google 5
我也尝试过:
(async () => {
await findSolution();
console.log("Done!");
})();
结果相同(Done! 打印在第一行)。
另一个尝试:
function findSolution(callback) {
for (let j = 0; j < 10; j++) {
askGoogle(j);
}
callback();
}
findSolution(() => {
console.log("Done!");
})
结果相同(Done! 被打印为第一行)。
为什么我的代码没有按预期工作(Done! 消息是输出中的最后一行),我该如何解决?
【问题讨论】:
-
查看
Promise对象,特别是Promise.all
标签: javascript node.js asynchronous