Run functions that return Promise "synchronously" and "repeatedly"

If you are implementing in js, a little heavy processing will be performed automatically “asynchronously”.

There are many times when you are happy with it, but if you run it repeatedly, it will take a little ingenuity to implement it, such as running it again using the results of the previous run.

This problem and solution

This time, when executing repeatedly, consider the case of executing again using the result of the previous execution.

If the number of repetitions is confirmed, or if you do not want to use the previous execution results and do not want to run in parallel, it is easy to use Promise.all() etc.

Also, if a synchronous execution version of an asynchronous execution function (such as fs.readFileSync()) is available, while and it will be solved.

However, there are many things that are not prepared.

For the above reasons, this time I will implement the approach of executing a function that returns Promise with async/await and waiting for the end, and then using the return value to decide the next execution.

async/await

An async function is a function declared with the async keyword, and the await keyword is permitted within them. The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.

Async functions may also be defined as expressions.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

Consider running slowFuc() and using its return value as the next run-time argument.

async function sample() {
  let result

while (true) {
    result = await slowFunc(next) // slowFunc() returns Promise
    let next = result.next

if (result.length == 0) {
      Break out when loop exit condition is met
      break
    }
  }
}

sample() // Run

Summary

It was easier to implement than I thought.
async/await is surprisingly often used, so it is necessary to be able to use it well.

Reference

async function - JavaScript | MDN
The async function declaration creates a binding of a new async function to a given name. The await keyword is permitted...
タイトルとURLをコピーしました