0

Question:
Is it possible to wait for an async function that starts new async functions?

Details:
I have looked up a bunch of ways to wait for an async function to finish before continuing the code, or running a specific function or code block. But one thing have bugged me for a very long time - I do not know whether new async functions started are also being waited for, or if they require their own piece of code to be taken into account.

Pseudocode:

var value = 1;
af1();
alert(value);

async function af1(){
    af2();
}

async function af2(){
    af3();
}

async function af3(){
    value = 2;
}

I dont know if this is a good example (or even the right syntax), but picture the async functions as some ajax requests that takes some time to finish. I have a feeling that if you add a jQuery deferred on af1, it will only wait for af1 and ignore af2 and af3. I am also using an external javascript file for some of the functions, and I dont really have control over what new functions are started in there.

So again, is it possible to just wrap all of this into something and run some code after all is done? Or am I mistaken about jQuery's deferred and .done functions??

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
mathkid91
  • 659
  • 2
  • 10
  • 27

3 Answers3

1

No, async functions are not awaited when called. They just return a promise.

Inside an async function - that's their advantage - you can explicitly await promises, including those that are returned from other async functions.

Your code should have been written using return values, like this:

(async function() { // neccessary to use await
    value = await af1();
    alert(value);
}());
af1().then(alert); // or just using promise syntax

async function af1(){
    return af2();
}
async function af2(){
    return af3();
}
async function af3(){
    return 2; // or maybe rather something like
    return $.ajax(…);
}

But you don't need return values, you can use await as well for your closure approach:

(async function() {
    var value = 1;
    await af1();
//  ^^^^^
    alert(value);

    async function af1(){
        await af2();
    }
    async function af2(){
        await af3();
    }
    async function af3(){
        value = 2; // or maybe rather something like
        value = await $.ajax(…);
    }
}())
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • A function that returns a `Promise` is what I would call async, but not all async functions return a `Promise`. The can be callback based, CSP based, etc. – Björn Roberg Dec 01 '15 at 10:14
  • @BjörnRoberg: OP is talking about the new ES7-proposed `async function`s, which do. I highlighted the keyword to convey that I did not mean asynchronous functions in general. – Bergi Dec 01 '15 at 10:16
  • Its good to get confirmed that I must handle each function. I guess I will have to try dig some into the library I'm using. Thanks for answer! – mathkid91 Dec 01 '15 at 10:18
  • @mathkid91: If you're using a library that doesn't support promises (or at least, A+ compatible thenables, like jQuery does), have a look at [promisification, i.e. converting a callback API to promises](http://stackoverflow.com/q/22519784/1048572). Otherwise, the transpiled `async await` should work out of the box. – Bergi Dec 01 '15 at 10:28
1

Use this git js ASync

How to use

Async provides around 20 functions that include the usual 'functional' suspects (map, reduce, filter, each…) as well as some common patterns for asynchronous control flow (parallel, series, waterfall…). All these functions assume you follow the Node.js convention of providing a single callback as the last argument of your async function.

Quick Examples

async.map(['file1','file2','file3'], fs.stat, function(err, results){
    // results is now an array of stats for each file
});

async.filter(['file1','file2','file3'], fs.exists, function(results){
    // results now equals an array of the existing files
});

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

async.series([
    function(){ ... },
    function(){ ... }
]);

There are many more functions available so take a look at the docs below for a full list. This module aims to be comprehensive, so if you feel anything is missing please create a GitHub issue for it.

Read More

Community
  • 1
  • 1
O-mkar
  • 5,430
  • 8
  • 37
  • 61
0

Apart from above examples, look at below code sample. concept of async and wait would be more clear.

async function doWork(){
    try {
        const response = await makeRequest('facebook'); //using await will wait until the response returned from the makeRequest function
        //console.log('Response Received' + response );

        const response2 = await makeRequest('google');
        //console.log('Response2 Received' + response2 );
    } catch(err) {
        alert(err);
    }
}

function makeRequest(str){
    //function body that takes time to process, eg: server call
    return "making request to " + str;
}

doWork();