Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: execute async function one by one

I have a simple "async" JS function:

function asyncFunc(i) {
    setTimeout(function () {
        console.log(i);
    }, 1000);
}

if I want to execute this asyncFunc 5 times in a for loop, i.e. log 1 - 5 per second, and totally costs 5 seconds.

1

2

3

4

5

I know jQuery's when().done() can do that however if I am in a environment with NO 3rd party JS libraries, what is the simplest and elegant way to achieve this?

Actually for example I want to write a util function which accepts an array of async functions, and this util function can execute passed in functions one by one:

function execAsyncTasks([asyncTask1, asyncTask2, asyncTask3]) {
    asyncTask1();
    // Wait until asyncTask1 finished
    asyncTask2();
    // Wait until asyncTask2 finished
    asyncTask3();
    // Wait until asyncTask3 finished
}
like image 455
Wayne Ye Avatar asked Nov 27 '12 11:11

Wayne Ye


People also ask

How do I run a one by one function in JavaScript?

Step1() is executing a json and appends details to html, Step2() is executing another json and appends info in the divs created by Step1() and Step3() simply hides a loading animation. They will be executed sequentially since JavaScript is single-threaded. Or, at least what people commonly make use of.

Do async functions run in parallel?

You can call multiple asynchronous functions without awaiting them. This will execute them in parallel. While doing so, save the returned promises in variables, and await them at some point either individually or using Promise.

How do you call async function?

Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.


2 Answers

You can use Async module:

https://github.com/caolan/async

async.parallel([
    function(){ ... },
    function(){ ... }
], callback);

async.series([
    function(){ ... },
    function(){ ... }
]);
like image 40
luin Avatar answered Oct 03 '22 20:10

luin


All your tasks will have to implement some sort of callback mechanism, because that's the only way you'll ever know that an asynchronous task has been completed. Having that, you could do something like:

function executeTasks() {
    var tasks = Array.prototype.concat.apply([], arguments);
    var task = tasks.shift();
    task(function() {
        if(tasks.length > 0)
            executeTasks.apply(this, tasks);
    });
}

executeTasks(t1, t2, t3, t4);

Demo

like image 80
David Hedlund Avatar answered Oct 03 '22 19:10

David Hedlund