2

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);
user9550188
  • 77
  • 1
  • 2
  • 9
  • Possible duplicate of [How do I convert an existing callback API to promises?](https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises) – CertainPerformance Sep 05 '19 at 07:08
  • Function a should also be a async function and give await for settimeout. Using await means ur gonna return a promis – subramanian Sep 05 '19 at 07:25

3 Answers3

1

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);
Saurabh Yadav
  • 3,303
  • 1
  • 10
  • 20
0
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);
Nayan Patel
  • 1,683
  • 25
  • 27
0

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);
mohammad javad ahmadi
  • 2,031
  • 1
  • 10
  • 27