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