LoginSignup
0
0

Mix usage of Promise async-await and then-catch

Last updated at Posted at 2020-03-16

Reference


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

// just use async-await
async function apicall() {
  try {
    const result = await myPromise(3)
    console.log(result)
  }
  catch (error) { // undefined & exception
    console.log(error)
  }
}

// use async-await and then-catch
async function apicall2() {
  const result = await myPromise(9)
  .then((re) => { return re; })
  .catch((error) => {
    console.log(error)
    return Promise.reject([]);
  })

  console.log(`result2: ${result}`)
}

async function apicall3() {
  const result = await myPromise(8).catch((error) => {
    console.log(error)
  })

  console.log(`result3: ${result}`)
}

apicall3();
apicall2();

apicall();

Those ways are avaliable to perform, but I personally prefer apicall3() because async-await is a wrapper to return resovled data back.

It make more sences and be clearer than apicall2() when you want to use both await and Promise.then() methods.


async function apicall0() {
    const result = await myPromise(3)
    if(result===undefined){
        console.log('error')
    }
    console.log(result)
// DeprecationWarning: Unhandled promise rejections are deprecated. 
//In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
}

apicall0(); // terminated in error

Reference

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0