简体   繁体   English

一起使用 async await and.then

[英]using async await and .then together

Is there any harm in using async/await and .then().catch() together such as:一起使用async/await.then().catch()是否有任何危害,例如:

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

I always use async/await and .catch() instead of using async/await and try/catch to make code compactly.我总是使用async/await.catch()而不是使用async/awaittry/catch来紧凑地制作代码。

 async function asyncTask() { throw new Error('network') } async function main() { const result = await asyncTask().catch(error => console.error(error)); console.log('result:', result) } main();

If you want to get a fallback value when an error happened, you can ignore the error and return a value inside the .catch() method如果你想在错误发生时得到一个回退值,你可以忽略错误并在.catch()方法中返回一个值

 async function asyncTask() { throw new Error('network') } async function main() { const result = await asyncTask().catch(_ => 'fallback value'); console.log('result:', result) } main();

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 表达式,该表达式暂停异步函数的执行并等待传递的 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).正如您从下面的示例中看到的,您可以使用两种方法来处理等待结果和错误,关键字 await 使 JavaScript 等待,直到该承诺解决并返回其结果(您从已解决的承诺中获得一种)。因此,没有任何危害(我不完全理解你在这里所说的伤害是什么)。

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

For further reference have a look at- MDN DOCS如需进一步参考,请查看- MDN DOCS

If you use Async/await you don't need to chain .then() just store the result returned by you resolve() in a variable ( response in the example) but if you want to handle the errors you have to try/catch your code :如果您使用 Async/await,则不需要链接.then()只需将您resolve()返回的结果存储在变量中(示例中的response ),但如果您想处理错误,则必须尝试/捕获你的代码:

async function f() {

  try {
    let response = await fetch('http://no-such-url');
  } catch(err) {
    alert(err); // TypeError: failed to fetch
  }
}

in your promise use:在你的承诺中使用:

throw new Error("oops!");

Or或者

Promise.reject(new Error("Whoops!"));

Don't want to raise the dead, but want to point out that using await along with a then chain means that the result of:不想复活死者,但想指出将awaitthen链一起使用意味着以下结果:

const x = await someAsyncFn().then(() => doSomeLogging());

The value of x is assigned the return value of .then , which wasn't super intuitive to me. x的值被分配了.then的返回值,这对我来说不是很直观。

I don't think mixed use async/await + then is a good idea.我不认为混合使用 async/await + then 是个好主意。 Especially when you focus on the async func's res, mixed use will bring some risk to distort your res silently.尤其是当你专注于 async func 的 res 时,混合使用会带来一些风险,悄悄地扭曲你的 res。

example:例子:

const res = await fetchData().then(()=>{return "something else"}).catch((err)=>{});

console.log(res); // not expected res data but something else

So, mixed use is dangerous , by the way, it'll do harm to read codes.所以,混合使用是危险的,顺便说一下,它会损害阅读代码。

there is no harm, but it's more code and harder to read, you can do this instead:没有害处,但它的代码更多且更难阅读,您可以这样做:

async apiCall(params) {
 try{
   var results = await this.anotherCall()
    return results;
 } catch(err){
   //do something with the error
 }
}

although I'm not sure what you are trying to do here, but returning the results in the try block only means that the function may return undefined in error cases.虽然我不确定您在这里尝试做什么,但在 try 块中返回results仅意味着 function 在错误情况下可能会返回 undefined 。

also it's important to remember that async functions always return a promise, so to use the apiCall function you have 2 ways of doing it:同样重要的是要记住异步函数总是返回 promise,所以要使用apiCall function,你有两种方法:

// 1- using .then to access the returned value
apiCall().then(results => {
   if(results){
      //doing something with the results
  }
})

// 2- awaiting the function inside another async function
async anotherFunction(){
  const results = await apiCall();
  if(results){
      //doing something with the results
  }
}

and using if(results) ensures that you are dealing with something other than undefined并使用if(results)确保您处理的不是 undefined

Just to add to this set of answers I always use await with then to make code more readable like so(aws example):只是为了添加到这组答案中,我总是使用 await 和 then 来使代码更具可读性(aws 示例):

I found this code snippet years ago(to function), probably somewhere on stack, I just can't remember where!几年前我发现了这个代码片段(功能),可能在堆栈的某个地方,我只是不记得在哪里!

async function myFunction(){
  var params = ....
  
  // either err will be null and data will have a value or if an exception was caused then data will be null and err will contain the information from the catch.
  let [err, result] = await to(route53.changeResourceRecordSets(params).promise())

  if(err){

    // handle the error
  }

  // carry on
}

to(promise){ // dunno why I called "to" call it anything you like.
  return promise.then((data) => {
  return [null, data]
 }).catch(err => [err])
}


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM