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

查看:2101
本文介绍了一起使用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;
  }

推荐答案

异步函数可以包含一个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结果和错误,关键字await使JavaScript等待该promise成立并返回其结果(您可以从已解决的promise中获得一种).没什么害处(我不完全理解您在这里所说的害处).

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天全站免登陆