When should i use ensureAsync
Hi,
Sometimes i received "Stack overflow", after looking for answers i see the function "ensureAsync", it solved my problem.
I'd like to know where this should be used, I have many asynchronous functions and sometimes I still get this error, so, which asynchronous function should I use "ensureAsync"?
Example:
async.whilst(
() => { return true; },
async.ensureAsync((callback) => { callback(); }),
(err) => { callback(err, this.result()); }
);
async.ensureAsync is a wrapper for synchronous functions to convert them to asynchronous functions that can then be passed to other methods. The "Stack Overflow" error is caused by passing synchronous callbacks to the async library's functions, as JavaScript can only run so many operations per tick of the event loop — asynchronous functions are executed during the next tick of the loop, meaning that they don't bog down a single tick with their functions; useful for a) performing a task when certain data is retrieved and you don't know when it will be retrieved, and b) ensuring that executing a function possibly hundreds of times does not result in the script becoming extremely slow.
* This is all based off of my own knowledge, of course, but the part about async.ensureAsync is correct to the documentation's description.
TL;DR use async.ensureAsync when passing a synchronous function to the async library's functions.
I think this should be documented in async documentation, especially on doWhilst, which takes test method in synchronous mode, but called on async lib