How to use the EnsureAsync Function in JavaScript's async module
EnsureAsync
The ensureAsync function in the async module wraps an async function and ensure that it calls its callback on a later tick of the events cycle. This prevents stack overflows caused by function calls.
Usage
The following example shows how the ensureAsync function is used.
import ensureAsync from 'async/ensureAsync';// Defining callback functionvar print = (val => console.log(val));// Defining async functionasync function helloWorld(value, callback){callback(value);}// Running ensureAsyncvar foo = ensureAsync(helloWorld);// Calling resultant functionfoo("Hello World 1!", print);// Demonstrating defferalhelloWorld("Hello World 2!", print);
This example attempts to demonstrate how ensureAsync is used and how it delays its execution. The helloWorld function is wrapped by ensureAsync, and the resultant function, foo, is called along with the unwrapped helloWorld function. Doing so results in similar levels of overhead in both function calls. However, possibly due to the delay in the wrapped function, the second unwrapped function call gets executed quicker despite being called after foo (the wrapped function).
One thing to note is that the function to be wrapped using ensureAsync (helloWorld in this case) should have its other arguments before the callback. So, in this example, the value to be printed is positioned before the callback in the function declaration.
Free Resources