javascript - js - 如何在 Promise .then() 中调用异步函数

标签 javascript asynchronous promise async-await

首先,我不得不提一下,我已经在 stackoverflow 中查看了许多问题,但很多问题并没有回答我的问题。更不用说很多人甚至没有答案。

如何实现以下目标,确保 functionB()functionA() 之后执行完成?

注意:我不想将我的异步函数转换为 new Promise(resolve=>{...})
因为我必须转换 someServiceThatMakesHTTPCall()以及调用堆栈中的任何其他异步函数,这是一个很大的变化。

  function functionThatCannotHaveAsyncKeyword() {
      functionA()
        .then(async function() {
            await functionB();
        })
        .then(function() {
            console.log('last');
        });
  }

  async function functionA() {
      console.log('first');
      await someServiceThatMakesHTTPCall();
  }

  async function functionB() {
      console.log('second');
      await someServiceThatMakesHTTPCall();
  }

最佳答案

您使用 await 的方法在 async then回调将起作用,但如果您只想调用 async,它会变得不必要地复杂。函数并使其结果通过链传播。但是,如果您正在做其他事情并想要 async 的语法优势功能,没问题。我稍后再谈。async函数返回 promise ,因此您只需返回调用函数的结果:

function functionThatCannotHaveAsyncKeyword() {
    functionA()
        .then(function() {
            return functionB(someArgument);
        })
        .then(function() {
            console.log('last');
        }); // <=== Note: You need a `catch` here, or this function needs
            // to return the promise chain to its caller so its caller can
            // handle errors
}
如果你想通过functionA的分辨率值转换为 functionB ,你可以更直接地做到这一点:
functionA()
    .then(functionB)
    // ...
当您从 then 返回 promise 时回调,调用 then 创建的 promise 已解决您返回的 promise :它将等待另一个 promise 解决,然后以相同的方式解决。
例子:

const wait = (duration, ...args) => new Promise(resolve => {
    setTimeout(resolve, duration, ...args);
});

async function functionA() {
    await wait(500);
    return 42;
}

async function functionB() {
    await wait(200);
    return "answer";
}

functionB()
.then(result => {
    console.log(result); // "answer"
    return functionA();
})
.then(result => {
    console.log(result); // 42
})
.catch(error => {
    // ...handle error...
});

使用 async 回到您的方法then回调:这也有效,并且在您做更多事情时有意义:

const wait = (duration, ...args) => new Promise(resolve => {
   setTimeout(resolve, duration, ...args);
});

async function functionA() {
    await wait(500);
    return 42;
}

async function functionB() {
    await wait(200);
    return "answer";
}

functionB()
.then(async (result) => {
    console.log(result); // "answer"
    const v = await functionA();
    if (v < 60) {
        console.log("Waiting 400ms...");
        await wait(400);
        console.log("Done waiting");
    }
    console.log(v);      // 42
})
.catch(error => {
    // ...handle error...
});

关于javascript - js - 如何在 Promise .then() 中调用异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54901478/

相关文章:

javascript - 表格拖放(仅保留一列)

map 中的 JavaScript map 等待响应

javascript - 在这种情况下如何维护类似 Promise 的 API?

javascript - Ember.js 将数据存储中的两个对象合并为一个字符串

javascript - html 中的 idm_frm 属性是什么?

javascript - 存储整数列表的内存有效方式

javascript - 从 Javascript 调用 PHP 函数时出现问题

Scala Future 和 TimeoutException : how to know the root cause?

javascript - Action 必须是普通对象。使用自定义中间件

backbone.js - 在 "reset"事件后使用 Promises 将主干绑定(bind)到 "fetch"