В приложении, которое я создаю, часто бывают отказы от обещаний, которые не имеют решающего значения. Поэтому я хочу продолжить с последующим кодом в блоке finally . Я обнаружил, что переменные в блоке затем и catch доступны в блоке finally без необходимости делать их глобальными. Было бы разумно использовать эти переменные в блоке finally или это не элегантно?
function promiseFunction1(input) {
return new Promise((resolve, reject) => {
if (input === 1) resolve("resolution from promiseFunction1")
if (input === 2) reject("rejection from promiseFunction1")
})
}
var maininput =1
promiseFunction1(maininput)
.then((result)=>{
//ideal outcome
resultCapturedInThen = result
})
.catch((error)=>{
console.log(`Warning: soemthing bad happened, but let's carry on`)
resultCapturedInThen = null
})
.finally(()=>{
if (resultCapturedInThen)
{
console.log(`result of promiseFunction1 in finally is ${resultCapturedInThen}`)
}
})
CONSOLE OUTPUT
____________________________________________________________
results
**if maininput is equal to 1**
result of promiseFunction1 in finally is resolution from promiseFunction1
**if maininput is equal to 2**
Warning: soemthing bad happened, but let's carry on