【问题标题】:Do we use await on async functions which use await?我们是否在使用 await 的异步函数上使用 await?
【发布时间】:2021-03-27 19:08:56
【问题描述】:

我有一个 Rest API 端点 /foo/bar,我从异步函数 bar() 调用它,我从另一个函数 foo () 调用该函数,就像这样

async function bar () {
    let result;

    result = await $.ajax({}); /* pseudocode only */
    return result;
}

function foo () {
    let result;

    result = bar ();
    console.log ('This should display before the result, not after it');
    console.log (result);
    console.log ('This should display after the result, not before it');

foo();
 

我得到不一致的结果,我想知道是不是因为我需要像这样使 foo 异步

async function bar () {
    let result;

    result = await $.ajax({}); /* pseudocode only */
    return result;
}

async function foo () {
    let result;

    result = await bar ();
    console.log ('This should display before the result, not after it');
    console.log (result);
    console.log ('This should display after the result, not after it');

foo();

基本上我的问题是异步函数中的 await 是否会呈现该函数同步(即它阻塞调用函数直到 await 返回)?

【问题讨论】:

  • 是的 - 否则你只会得到承诺`
  • 你不能在 javascript 中阻止函数
  • 是的,await 停止执行函数(并且只停止函数!)直到 promise 解决。然而,这实际上是异步函数异步的原因,因为您不知道何时继续执行。

标签: javascript ajax asynchronous


【解决方案1】:

你是对的。异步函数将返回一个 Promise,因此,如果您想等待异步函数的响应,则需要 await。

【讨论】:

    【解决方案2】:

    async 函数定义为 returns a Promise,因此您处理结果的方式与任何其他 Promise 相同。

    这基本上意味着您要么使用async/await 执行第二个 sn-p 中的操作:

    async function foo () {
        let result;
    
        result = await bar ();
        console.log (result);
    }
    

    或者你也可以使用.then:

    function foo() {
        bar().then(result => console.log(result));
    }
    

    【讨论】:

      猜你喜欢
      • 2020-05-14
      • 2017-02-02
      • 1970-01-01
      • 2015-06-28
      • 2022-01-03
      • 1970-01-01
      • 2012-12-06
      • 2019-05-31
      • 1970-01-01
      相关资源
      最近更新 更多