【问题标题】:Javascript: print message after all http requests have been send, asynchronouslyJavascript:在发送所有http请求后异步打印消息
【发布时间】: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


【解决方案1】:

您可以通过多种方式做到这一点。

也许最简单的是在“askGoogle”函数中返回一个promise,并在“findSolution”中执行“Promise.all”(在获得的promise列表上)

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!");

【讨论】:

  • 我也对回调解决方案感兴趣
猜你喜欢
  • 1970-01-01
  • 2012-12-23
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多