如何等待函数在Nide.js的while循环内完全执行

时间:2019-10-02 09:47:21

标签: javascript node.js async-await

在函数完全执行之后,我想接下来进行迭代。但是,循环会在函数完全执行之前进行迭代。我用过async / await。但没有运气。

function getdata(a,b)
{
    var somevalue = '';
    request(req,function(){
        //somecode
        //assign value to 'somevalue'
    });
    return somevalue;
}

function abc()
{
    var value = '';
    while(value!=='x')
    {
        value = getdata(a,b);
    }
}


//I've tried this way

async function getdata(a,b)
{
    var somevalue = '';
    request(req,function(){
        //somecode
        //assign value to 'somevalue'
    });
    return somevalue;
}

async function abc()
{
    var value = '';
    while(value!=='x')
    {
        value = await getdata(a,b);
    }
}

1 个答案:

答案 0 :(得分:0)

使用仅在执行完成后返回的回调函数

List<List<Product>> query = (from lists in ListOfList
                            where lists.Sum(x => x.factor) <= 10
                            orderby lists.Sum(x => x.cost) descending
                            select lists).ToList();

List<Product> tempList = query.FirstOrDefault();