How comes (Microtask queue) while using Promises in js?

What is microtask queue while handling Promise, Where and when is it mostly used? I am unable to manage many asynchronous tasks with Promises

»Javascript @jeph6

» 2 answers  » 89 views   

Add photos

Gadrawin • 2 months ago
There is ES8 term, According to ECMA standard, and ES docs define that All promise jobs are always on the queue internally. Therefore, This situaton means that All Promise handlers such as .then, catch and finally should always be on that queue and each one of these handlers has to wait for another one(previous) to complete its execution then the next one starts being executed as well. That's how Promise function works, Even if you use Promise from the beginning and you add other code example, console.log("Hello") at the end, that code will run first and then Promise comes next. Remember Promise itself uses FIFO method. After other code finishes its execution. Briefly First handler or enqueued handler will run, then the second. example: let promise = Promise.resolve(); promise.then(() => console.log("First p handler!")); promise.then(() => console.log("Second p handler!")); alert("Another code!"); Here, the code inside alert will be executed at first, then "First p handler" runs next and so on... What if you are getting output in unexpected order? Solution: Apply Microtask queue. Microtask queue help you in managing all of your asynchronous tasks, With this example, How can we make code in "alert" run after promise done? Promise.resolve() .then(() => alert("First p handler!")) .then(() => alert("Second p handler!")) .then(() => alert("Another code!")); In order to understand deeply microtask queuing read more on site and use this link For advanced usage if you plan to use Node.js, you will need “event loop” and “macrotasks” as they are used hand in hand. »

0  Dislike  •  Reply

Codeveloper • 2 months ago
There is a solution to prevent you from struggling with Promise. Why can't you use Async and Await instead, as better and modern way to handle promise. Async function will make sure that promise is returned and get await function wait for promise to be settled. Give it a try, has good features.
Async and await in action async function add(num1, num2) { let prom = new Promise((resolve, reject) => { resolve(num1 + num2); }); let result = await prom; alert(result); } add(4, 7); // 11 add(10, 15); // 25
Promise handling is always asynchronous, as all promise actions pass through the internal “promise jobs” queue, also called “microtask queue” (ES8 term). So .then/catch/finally handlers are always called after the current code has finished. »

0  Dislike  •  Reply

Back to top

[SHARE THIS POST]: The post's archived Spread it to others!

Posted under this donnektish »
This community is about sharing contents such as questions and answers discussing about Javascript and TypeScript, ES5, ES6
62 people joined this donnektish

Maintain social distancing, to avoid Covid19