[英]Javascript: print message after all http requests have been send, asynchronously
我有一個方法askGoogle
可以模擬發送http
請求。 我在 for 循環中調用askGoogle
10 次。 每個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!");
output:
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”function 中返回 promise,並在“findSolution”中執行“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!");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.