using async await and .then together

38,255

Solution 1

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.

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

For further reference have a look at-MDN DOCS

Solution 2

I always use async/await and .catch() instead of using async/await and try/catch to make code compactly.

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

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

main();

Solution 3

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:

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

The value of x is assigned the return value of .then (i.e. undefined, if doSomeLogging is void) which wasn't super intuitive to me.

Solution 4

I don't think mixed use async/await + then is a good idea. Especially when you focus on the async func's res, mixed use will bring some risk to distort your res silently.

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.

Solution 5

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 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!"));

Share:
38,255
PixelPaul
Author by

PixelPaul

Updated on July 20, 2021

Comments

  • PixelPaul
    PixelPaul almost 3 years

    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;
      }
    
  • scavenger
    scavenger over 3 years
    i use that all the time and it's better than using .then + another anonymous async function that makes the whole thing illegible
  • quantumferret
    quantumferret over 3 years
    Your way hadn't occurred to me, but I really like it! I usually mix them the opposite way, having a try / catch statement with await and using .then to perform an additional transformation or whatever on the resolved promise.
  • Jeff Padgett
    Jeff Padgett over 3 years
    Let's say you have more code after the result = line. Let's say that there was an error. Is result then undefined?
  • slideshowp2
    slideshowp2 about 3 years
    @JeffPadgett Yes, you can return a fallback value from the .catch() method
  • Jeff Padgett
    Jeff Padgett about 3 years
    Do you mind updating your answer with a fallback from the .catch() method?
  • slideshowp2
    slideshowp2 about 3 years
    @JeffPadgett Updated answer.
  • I_love_vegetables
    I_love_vegetables almost 3 years
    Suggestion : add code fences and the language identifier to highlight the code and make it more readable.
  • ndh103
    ndh103 over 2 years
    Really nice and compact, the fallback value is a very good way to avoid Typescript error