【问题标题】:serial await requests in a return run in parallel?并行返回中的串行等待请求?
【发布时间】:2017-08-14 03:53:09
【问题描述】:

与某人讨论并遇到了这个奇怪的问题:

const wait = async () => new Promise(resolve => setTimeout(resolve, 1000));

async function case1() {
  const {a, b} = {a: await wait(), b: await wait()};
  return {a, b};
}

async function case2() {
  return {a: await wait(), b: await wait()};
}

async function case3() {
  const {a, b} = {a: wait(), b: wait()};
  return {a: await a, b: await b};
}

async function case4() {
  const {a, b} = {a: wait(), b: wait()};
  const {c, d} = {c: await a, d: await b};
  return {c, d};
}

function test() {
  const start = new Date();

  case1().then(() => console.log('case1:', +new Date() - start));
  case2().then(() => console.log('case2:', +new Date() - start));
  case3().then(() => console.log('case3:', +new Date() - start));
  case4().then(() => console.log('case4:', +new Date() - start));
}

case1case2 都在 2 秒内运行。 case3case4 在 1 秒内运行。

是不是有什么奇怪的隐含Promise.all之类的??

【问题讨论】:

    标签: javascript async-await


    【解决方案1】:

    您在case3case4 处调用函数wait() 而不使用await。这就是区别。

    【讨论】:

    • 它们在所有情况下都被调用并且都返回完全相同的东西
    • 不,它们不一样。你打电话给wait(),没有awaitcase3()case4()分别打电话给const {a, b} = {a: wait(), b: wait()};const {a, b} = {a: wait(), b: wait()};
    • 是的,他们是。它们中都有一个await,那么为什么{await fn(), await fn()} 串行运行它们而{await result, await result} 并行运行它们呢?
    • 不确定为什么您得出结论它们是相同的?他们不一样。您忽略了在解构赋值的每个case3()case4() 调用中使用await,然后在下一行使用await,尽管调用已经在上一行进行了。
    【解决方案2】:

    在 case#3 中,wait() 函数会立即被调用,所以只有 1 秒的超时时间(对于他们两个),而在其他两个(case#1 和 case#2)中,await 将“做它的工作”并等待异步调用返回。

    正如您在此处看到的,console.log(Date()) 会立即为这两个调用调用。

    const wait = async () => new Promise(resolve => console.log(Date()) || setTimeout(resolve, 1000));
    
    async function case3() {
      const {a, b} = {a: wait(), b: wait()};
      return {a: await a, b: await b};
    }
    
    function test() {
      const start = new Date();
      case3().then(() => console.log('case3:', +new Date() - start));
    }
    test();

    这里正在使用await进行同步:

    const wait = async () => new Promise(resolve => console.log(Date()) || setTimeout(resolve, 1000));
    
    async function case1() {
      const {a, b} = {a: await wait(), b: await wait()};
      return {a, b};
    }
    
    
    function test() {
      const start = new Date();
    
      case1().then(() => console.log('case1:', +new Date() - start));
    }
    test();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-09
      • 2016-04-13
      • 2023-04-05
      • 2013-05-13
      • 2019-12-10
      • 2021-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多