user9550188
user9550188

Reputation: 85

Nodejs async await for loop

How can I wait until the function a is complete, but is not working as I expected.

Here is my code:

var start = Date.now();

function a() {
    setTimeout(function(){ console.log(Date.now() - start); }, 500);
    for(var i=0; i<100; i++) {
        console.log(i);
        //
    }
}

const main = async () => {
    await a();

    console.log("Done");

};
main().catch(console.error);

Upvotes: 2

Views: 787

Answers (3)

mohammad javad ahmadi
mohammad javad ahmadi

Reputation: 2081

you can use q module for make promise also:

var q = require('q')
var start = Date.now();

function a() {
    let defer = q.defer()
    setTimeout(function(){ console.log(Date.now() - start); defer.resolve();}, 500)
    for(var i=0; i<100; i++) {
        console.log(i);
    }
    return defer.promise;
}

const main = async () => {
    await a();

    console.log("Done");

};
main().catch(console.error);

Upvotes: 0

Saurabh Yadav
Saurabh Yadav

Reputation: 3386

You have to return promise when you call await. The await operator is used to wait for a Promise. It can only be used inside an async function. Check here for more details:

async function

var start = Date.now();

    function a() {
        return new Promise(function(resolve, reject) {
            setTimeout(function(){ console.log(Date.now() - start); resolve()}, 500);
            for(var i=0; i<100; i++) {
                console.log(i);
                //
            }
        })    
    }

    const main = async () => {
        await a();
        console.log("Done");

    };
    main().catch(console.error);

Upvotes: 1

Nayan Patel
Nayan Patel

Reputation: 1761

var start = Date.now();

function a() {
    return new Promise((resolve, reject)=> {
        setTimeout(function(){ console.log(Date.now() - start); resolve() }, 500);
        for(var i=0; i<100; i++) {
            console.log(i);
            //
        }
    });
}

const main = async () => {
    await a();

    console.log("Done");

};
main().catch(console.error);

Upvotes: 0

Related Questions