Node.js异步等待循环

时间:2019-09-05 07:05:34

标签: node.js async-await

我如何才能等到功能a完成但不能按预期工作。

这是我的代码:

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);

3 个答案:

答案 0 :(得分:1)

您在致电等待时必须退还诺言。等待操作符用于等待Promise。它只能在异步函数中使用。在此处查看更多详细信息:

  

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);

答案 1 :(得分: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);

答案 2 :(得分:0)

您还可以使用q模块来做出承诺:

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);