Actually my main question was using Promise.prototype.catch()
in async/await
ES8
syntax, Undoubtedly Promise.prototype.then()
is existed in essence of async/await
syntax.
I searched about using Promise.prototype.catch()
in async/await
and found this:
async () => { try { const result1 = await firstAsynchronousFunction(); const result2 = await secondAsynchronousFunction(result1); console.log(result2); } catch(err) { throw new Error(`Something failed`); } }
And absolutely I knew about Promise
chaining, like:
new Promise((resolve) => { console.log(`Initial`); resolve(); }) .then(() => { console.log(`Task Number One`); }) .catch(() => { console.log(`Task in Error`); }) .finally(() => { console.log(`All Tasks is Done`); })
So, my question is how I can use finally
in async/await
syntax?
Introduction to the JavaScript Promise finally() methodcatch(error => { ... }) . finally(() => { ... }) The finally() method is always executed whether the promise is fulfilled or rejected. In other words, the finally() method is executed when the promise is settled.
async and await Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.
The finally() method of a Promise schedules a function, the callback function, to be called when the promise is settled. Like then() and catch() , it immediately returns an equivalent Promise object, allowing you to chain calls to another promise method, an operation called composition.
finally() method to the standard library. The finally() method lets you execute a callback function once the promise that it's called on has been settled (that is, it has been either fulfilled or rejected and is therefore no longer pending): somePromise. finally(() => { // Code });
this should work:
async () => { try { const result1 = await firstAsynchronousFunction(); const result2 = await secondAsynchronousFunction(result1); console.log(result2); } catch(err) { throw new Error(`Something failed`); } finally { console.log(`All Tasks is Done`); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With