Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Promise.prototype.finally() in async/await syntax?

Tags:

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?

like image 869
AmerllicA Avatar asked May 16 '18 14:05

AmerllicA


People also ask

How do you use promise finally?

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.

How do I use async await with promises?

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.

What does the finally () method on promise do?

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.

How do I use Finally in typescript?

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 });


1 Answers

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`);   } } 
like image 56
jcubic Avatar answered Dec 17 '22 10:12

jcubic