js-如何在Promise .then()中调用异步函数 [英] js - How to call an async function within a Promise .then()

查看:399
本文介绍了js-如何在Promise .then()中调用异步函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我不得不提到,我已经研究了stackoverflow中的许多问题,但是许多问题并没有回答我的问题.更不用说许多甚至没有答案.

First, I have to mention that I already look through many questions in stackoverflow, but many doesn't answer my question. Not to mention many doesn't even have an answer.

如何确保在 functionA()完成后执行 functionB()?

How do I achieve the following, making sure functionB() executes after functionA() finishes?


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


Note: I do not want to convert my async functions to new Promise(resolve=>{...})
because I'll have to convert the someServiceThatMakesHTTPCall() as well, and any other async functions within the call stack, which is a big change.

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

推荐答案

您在 async then 回调中使用 await 的方法可以工作,但是如果要执行的 all 调用 async 函数并使其结果通过链传播,则不必要的复杂.但是,如果您正在做其他事情,并且想要 async 函数的语法优势,那很好.我待会儿再讲.

Your approach using await in an async then callback will work, but it's unnecessarily complex if all you want to do is call the async function and have its result propagate through the chain. But if you are doing other things and want the syntax benefit of async functions, that's fine. I'll come back to that in a moment.

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

async functions returns promises, so you just return the result of calling your function:

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 ,则可以更直接地做到这一点:

If you want to pass functionA's resolution value into functionB, you can do it even more directly:

functionA()
    .then(functionB)
    // ...

当您从 then 回调中返回承诺时,将通过调用 then 创建的承诺解析为 您返回的承诺:它会等待其他诺言实现,然后以同样的方式实现.

When you return a promise from a then callback, the promise created by the call to then is resolved to the promise you return: it will wait for that other promise to settle, then settle the same way.

示例:

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 回调返回到您的方法:这也有效,并且在您做更多事情时有意义:

Coming back to your approach using an async then callback: That works too, and makes sense when you're doing more stuff:

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...
});

这篇关于js-如何在Promise .then()中调用异步函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆