Javascript:异步发送所有http请求后打印消息



我有一个方法askGoogle,它模拟发送http请求。我在for循环中调用askGoogle10次。每个askGoogle调用的执行时间都是随机的。

这10个请求是异步发送的,这意味着第二个请求不会等到第一个请求完成后再发送,等等。因此,有时第一个请求需要更长的时间才能完成,这会导致第四个或第八个请求提前执行。

我希望在所有请求完成后打印一条消息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!消息是输出中的最后一行(,我该如何修复它?

您可以通过多种方式实现这一点。

也许最简单的方法是在"askGoogle"函数中返回promise,并在"findSolution"(在获得的promise列表上(中执行"promise.all">

function askGoogle(i)  {
return new Promise( (resolve, reject) => {
setTimeout(() => {
const googleRequest = https.request("https://google.com", {
method: "GET"
});
googleRequest.once("error", err => {
console.log("Something happened!");
reject(err);
})
googleRequest.once("response", (stream) => {
stream.on("data", x => {
});
stream.on("end", () => {
resolve(i);
console.log("Done with google " + i);
i++;
})
})
googleRequest.end();
}, getRandomInt(0, 5_000));
});
}
function findSolution() {
const promises = [];
for (let j = 0; j < 10; j++) {
promises.push(askGoogle(j));
}
return Promise.all(promises);
}

现在,你可以做:

findSolution().then(() => {
console.log("Done!");
});  

await findSolution();  
console.log("Done!");

最新更新