【问题标题】:Getting parallel async/await to work javascript [duplicate]让并行异步/等待工作javascript [重复]
【发布时间】:2020-05-22 08:28:01
【问题描述】:

我正在尝试并行运行两个不相互依赖的异步操作,但我似乎无法让它工作。

const activity = fetchActivity(...)
const progress = fetchProgress(...)
await activity
await progress

当我打印activityprogress 的属性时,它们都是未定义的。

当我这样运行它时,属性会显示出来。

const activity = await fetchActivity(...)
const progress = await fetchProgress(...)

我在想某种并行方法awaits 没有正确等待,因为当我将对象记录到控制台时,它们最终会显示出来,但直接记录属性不起作用。

更新


显然我无法回答我自己的问题,因为它已关闭,但首先要感谢那些将我引导到正确答案的人,尽管没有回答我的问题。

虽然下面给出了我的问题的实际解决方案,但这里给出了不使用此方法的原因:Waiting for more than one concurrent await operation,而我应该追求已经在各处提到的解决方案。

回答:


awaits 的值没有存储在变量中,所以以后直接访问它是行不通的。

const activity = fetchActivity(...)
const progress = fetchProgress(...)
const activityData = await activity
const progressData = await progress

【问题讨论】:

  • 这能回答你的问题吗? Call async/await functions in parallel
  • @GrafiCode 那是别的东西
  • @ZohaibIjaz 那是什么?
  • 这是网上各种文章都建议的方法:我找不到好的atm,但是这篇freecodecamp.org/news/…提到了一点。 ctrl+f“等待披萨承诺”
  • @GrafiCode 我认为这会奏效,但这种方法有什么问题?如果 fetchProgress 花了 20 年,我想在 await activityawait progress 之间运行一些操作,该怎么办?

标签: javascript asynchronous async-await


【解决方案1】:

您可以改用 Promise.all():

例如:

await Promise.all([call1(), call2()]);

你可以这样存储结果:

let [res1, res2] = await Promise.all([call1(), call2()]);

希望对你有帮助!

【讨论】:

  • 它确实有效,但有没有办法使问题中提到的内容有效?假设 fetchProgress 花了 20 年时间,我想在 await activityawait progress 之间运行一些操作
【解决方案2】:

你的方法返回一个Promise

Promise是一个延迟对象,主要用于帮助处理异步操作。
这是必需的,因为 JS 是单线程环境。并且您不想阻塞主执行线程或长时间的异步操作。

const promise1 = fetchActivity(...); // 将返回一个承诺。

Promise 对象被解析时,您可以使用Promise.then 运行回调,也可以改用async/await

如果您选择等待 Promise ,它实际上会等到您传递到下一行,即使操作是异步的(例如线程没有被阻塞,但编码感觉是同步的)。

如果您不想等到结果,您可能会更喜欢使用Promise.then

const res1 = await promise1; 
const nextLine = 1+1; // will happen after the promise is resolved

promise1.then(res1 => // register callback and do something with the response).
const nextLine = 1+1; // will happen immediately 

现在了解Promise 是什么之后,就可以使用Promise.all 方法进行并行执行了。

Promise.all 接受一组承诺并返回一个承诺,当所有其他承诺都解决时,该承诺将被解决。

const fetchActivityPromise = fetchActivity(..)
const fetchProgressPromise = fetchProgress(..)
const promiseRes = Promise.all([fetchActivityPromise, fetchProgressPromise]);
promiseRes.then(r => ...)
console.log('here before the promiseRes.then was called');

【讨论】:

    猜你喜欢
    • 2021-12-08
    • 1970-01-01
    • 2018-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-06
    • 2018-04-17
    • 2019-10-29
    相关资源
    最近更新 更多