【问题标题】:How to wait for a specific result in an function while running other functions如何在运行其他函数时等待函数中的特定结果
【发布时间】:2019-03-05 20:56:57
【问题描述】:

我想在等待另一个响应时运行一些代码?

例子:

var obj = {};

await pre(obj);
await first(obj);
await second(obj);
await third(obj);

await function pre(obj) {self.something = "something";}
await function first(obj){...something...}
await function second(obj){...something...}
await function third(obj){...Do something with obj...}

我想不通的是,我如何运行 pre() 并完成其耗时的目标,同时运行 first() 和 second() 和 third() 但第三个将在 pre 完成后运行?

【问题讨论】:

  • async function pre()... 不是await function pre()...

标签: javascript node.js async-await


【解决方案1】:

您可以使用Promise.all 在运行third 之前并行运行所有中间步骤:

var obj = {};

await Promise.all([ pre(obj), first(obj), second(obj)]);
await third(obj);

如果我正确理解了您的问题,在 Promise.all 完成时,obj 将包含运行 prefirstsecond 的突变。

注意错误处理以及对obj 对象的非确定性访问。

【讨论】:

    【解决方案2】:

    我想不通的是,我如何运行 pre() 并完成其耗时的目标,同时运行 first() 和 second() 和 third() 但第三个将在 pre 完成后运行?

    基于这个问题,我的理解是你想要:

    1. 同时运行prefirstsecond
    2. 一旦pre 完成执行,然后运行third

    如果是这种情况,那么下面的代码将做到这一点:

    var obj = {test: "Test"};
    
    async function pre(obj) {console.log(`${pre.name} :`, obj); return obj;}
    async function first(obj)  {console.log(`${first.name} :`, obj)}
    async function second(obj) {console.log(`${second.name} :`, obj)}
    async function third(obj)  {console.log(`${third.name} :`, obj)}
    
    Promise.all([first(obj), second(obj), pre(obj).then(third)]);
    

    Promise.all() 函数接受一个函数数组,这些函数返回一个 Promise 并并行执行它们。注意pre(obj).then(third)。这将执行pre 函数,完成后将执行third 函数。

    【讨论】:

      【解决方案3】:
      var obj = {};
      
      async function pre(obj) {self.something = "something";}
      async function first(obj){...something...}
      async function second(obj){...something...}
      async function third(obj){...Do something with obj...}
      
      // use array destructuring to get the responses after promises resolve
      const [ preResponse, firstResponse, secondResponse ] = await Promise.all([
        pre(obj),
        first(obj),
        second(obj)
      ]);
      const thirdResponse = await third(obj);
      

      【讨论】:

        猜你喜欢
        • 2021-09-27
        • 1970-01-01
        • 2021-07-01
        • 1970-01-01
        • 2021-01-07
        • 1970-01-01
        • 1970-01-01
        • 2019-01-18
        • 1970-01-01
        相关资源
        最近更新 更多