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

时间:2019-02-27 08:55:53

标签: 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();
  }

3 个答案:

答案 0 :(得分:8)

您在await async回调中使用then的方法是可行的,但是如果您想做的 all 是调用{{1 }}函数并使其结果通过链传播。但是,如果您正在做其他事情,并且想要async函数的语法好处,那很好。我待会儿再讲。

async函数返回promise,因此您只需返回调用函数的结果即可:

async

如果要将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创建的承诺将作为您返回的承诺的一部分。

示例:

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(result => { console.log(result); // "answer" return functionA(); }) .then(result => { console.log(result); // 42 }) .catch(error => { // ...handle error... }); async回调返回到您的方法:这也有效,并且在您做更多事情时很有意义:

then

答案 1 :(得分:0)

如果someServiceThatMakesHTTPCall是异步的,则可以执行以下操作来避免所有这些情况:

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

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

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

答案 2 :(得分:0)

您可以在第一种方法中使用promise

function functionThatCannotHaveAsyncKeyword() {
    return new Promise(async(resolve, reject)=> {
          await functionA();
          await functionB();
          console.log('last');    
      });
  }

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

  async function functionB() {
      console.log('second');
      await someServiceThatMakesHTTPCall();
  }
相关问题