gpt4 book ai didi

javascript - Ajax Promise 是同时执行的,而不是顺序执行的

转载 作者:行者123 更新时间:2023-12-03 02:33:19 25 4
gpt4 key购买 nike

我使用一个向服务器发送一些请求的应用程序。

function createAjaxCall(data, done, fail) {
return $.post("process_watch.php", data).then(done).fail(fail);
}

function step1() {
return createAjax({ }, function(result) { console.log(result); return result; }, function() { });
}

function step2(res) {
return createAjax({ }, function(result) { console.log(result); return result; }, function() { });
}

...

有些请求需要一段时间(假设我在 PHP 中使用 sleep(1500);),如果这样做:

step1().then((data) => step2(data)).then((data) => step3(data)) then 将同时执行。

出了什么问题?

最佳答案

JavaScript 中没有任何并行的事情发生。它是一种并发语言。您编写的内容将串行执行(一个接一个)。需要 1500*3 毫秒才能完成(假设每个需要 500 毫秒)

step1().then((data) => step2(data)).then((data) => step3(data))

要使它们同时执行(在 js 中也称为并行),您应该执行以下操作。所有调用都将被发送以获取数据。当所有调用都解决时,promise 将进入 then-catch 链。这将需要 或多或少 1500 毫秒才能完成(假设每个需要 500 毫秒)

Promise.all([step1(),step2(),step3()]).then().catch()

关于javascript - Ajax Promise 是同时执行的,而不是顺序执行的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48642252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com