JSFiddle - React, Tailwind, and code Playground
by lid0
HTML
promises ( reject vs throw , try..catch vs Promise.catch )
JavaScript
/**
lidlanca
run different cases where a promise is rejected and throw right after.
Case A - run without .catch or try..catch ( will just exit)
Case B - run with try..catch, but without .catch ( will catch the reject value as error)
Case C - run with .catch and wrap in try..catch
will assign the rejected value to the awaiting variable as returned in .catch()
will NOT catch the thrown error in the wrapping try..catch
Case D - we run with .catch() only for a promise that only reject (no throw)
will set value to value returned by the .catch()
we can wrap in try..catch without .catch() if we need to know a reject happend
*/
function getP(t) {
return new Promise(function(res, rej) {
setTimeout(function() {
rej("REJECT")
throw ("FAILED")
}, 1000 * t)
})
};
function getPRejectOnly(t) {
return new Promise(function(res, rej) {
setTimeout(function() {
rej("REJECT")
}, 1000 * t)
})
};
async function runCases() {
console.log("<A>")
try {
await caseA()
} catch (e) {
//ignore so we can run the next case
}
console.log("</A>")
console.log("<B>")
try {
await caseB()
} catch (e) {
//ignore so we can run the next case
}
console.log("</B>")
console.log("<C>")
try {
await caseC()
} catch (eee) {
// can't catch the FAILED error even if we want to
console.log("C external catch:", eee)
}
console.log("</C>")
console.log("<D>")
try {
await caseD()
} catch (eee) {
// can't catch the FAILED error even if we want to
console.log("D external catch:", eee)
}
console.log("</D>")
}
async function caseA() {
var v = null
var v = await getP(1)
console.log("A value:", v)
}
async function caseB() {
var v = null
try {
var v = await getP(2)
} catch (e) {
console.log("B catch", e)
}
console.log("B value", v)
}
async function caseC() {
var v = null
try {
v = await getP(3).catch((val)...