Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to use the EnsureAsync Function in JavaScript's async module

Educative Answers Team


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.


The following example shows how the ensureAsync function is used.

import ensureAsync from 'async/ensureAsync';

// Defining callback function
var print = (val => console.log(val));

// Defining async function
async function helloWorld(value, callback){

// Running ensureAsync
var foo = ensureAsync(helloWorld);

// Calling resultant function
foo("Hello World 1!", print);

// Demonstrating defferal
helloWorld("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.


Copyright ©2022 Educative, Inc. All rights reserved

View all Courses

Keep Exploring