一起使用 async await 和 .then [英] using async await and .then together

查看:83
本文介绍了一起使用 async await 和 .then的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

async/await.then().catch() 一起使用是否有任何危害,例如:

Is there any harm in using async/await and .then().catch() together such as:

async apiCall(params) {
    var results = await this.anotherCall()
      .then(results => {
        //do any results transformations
        return results;
      })
      .catch(error => {
        //handle any errors here
      });
    return results;
  }

推荐答案

async 函数可以包含一个 await 表达式来暂停执行异步函数并等待传递的 Promise 的解析,然后恢复异步函数的执行和返回解析值.

An async function can contain an await expression that pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value.

正如您从下面的示例中看到的,您可以使用两种方法来处理等待结果和错误,关键字 await 使 JavaScript 等待,直到该承诺解决并返回其结果(您从已解决的承诺中获得一种).因此有没有害处(我不完全理解你在这里所说的害处).

As you can see from below example that you can use two ways to handle await result and errors,The keyword await makes JavaScript wait until that promise settles and returns its result (One you get from resolved promise).So as such there is no harm (I don't fully understand what you refer as harm here).

function returnpromise(val) {
  return new Promise((resolve, reject) => {
    if (val > 5) {
      resolve("resolved"); // fulfilled
    } else {
      reject("rejected"); // rejected
    }
  });
}

//This is how you handle errors in await
async function apicall() {
  try {
    console.log(await returnpromise(5))
  } catch (error) {
    console.log(error)
  }
}

async function apicall2() {
  let data = await returnpromise(2).catch((error) => {
    console.log(error)
  })
}

apicall2();
apicall();

要进一步参考,请查看-MDN DOCS

For further reference have a look at-MDN DOCS

这篇关于一起使用 async await 和 .then的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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