如何将此迭代更改为异步函数?

How to change this iteration into a async function?

此代码可能无法正常工作,因为与 mongo 的连接建立速度不够快。所以我认为我必须将它更改为 asnyc 函数。但绝对不知道从哪里开始。我是 Node 新手 Mongo

left
Julian Graber 900 1
windowsdemo 673 3
laptopDemo 640 4
IpadDemo 628 5

看起来应该是这样,但是 mongo 更新它每个排名都是相同的数字。

// function for giving rank
function giveRank(arrayArg,resultArg){
  // declaring and initilising variables
    let rank = 1;
    prev_rank = rank;
    position = 0;
    // displaying the headers in the console
    console.log('\n-------OUR RESULTS------\n');
    console.log('Name | Mark | Position\n');
    // looping through the rank array
    for (i = 0; i < arrayArg.length ; i ++) {
            /*
            If it is the first index, then automatically the position becomes 1.
            */
            if(i == 0) {
                position = rank;
            Ranking.find({name: arrayArg[i]}).then((data) => {
                if(data){
                updateRank(bla, bla, bla)
                }else{
                newRank(bla,bla,bla);
                }
            });
            
            /*
            if the value contained in `[i]` is not equal to `[i-1]`, increment the `rank` value and assign it to `position`.
            The `prev_rank` is assigned the `rank` value.
            */
            } else if(arrayArg[i] != arrayArg[i-1]) {
            rank ++;
            position = rank;
            prev_rank = rank;
            Ranking.find({name: arrayArg[i]}).then((data) => {
                if(data){
                updateRank(bla, bla, bla)
                }else{
                newRank(bla,bla,bla);
                }
            });
            
            /*
            Otherwise, if the value contained in `[i]` is equal to `[i-1]`,
            assign the position the value stored in the `prev_rank` variable then increment the value stored in the `rank` variable.*/
            } else {
                position = prev_rank;
                rank ++;
                Ranking.find({name: arrayArg[i]}).then((data) => {
                if(data){
                updateRank(bla, bla, bla)
                }else{
                newRank(bla,bla,bla);
                }
            });
            }
    }
}

要将 promise-chain-based 异步调用转换为 async/await 调用,您只需要做几件事:

  1. 使用async关键字将父函数转换为异步函数,例如:function myFunction (...) {}变成async function myFunction (...) {}

  2. 在函数调用前使用 await 关键字,如下所示:doStuff(...) 变为 await doStuff(...)

  3. 将参数转换为您的第一个 .then() 回调到异步调用的 return 值,像这样: doStuff().then((data) => {}) 变成 let data = await doStuff()

  4. .then() 回调的主体移动到响应赋值下方,如下所示:doStuff().then((data) => { console.log(data) }) 变为 let data = await doStuff(); console.log(data);

因此在您的示例中,转换其中一个函数将如下所示:

async function giveRank(arrayArg,resultArg){
...
...
  if(i == 0) {
    position = rank;
    let data = await Ranking.find({name: arrayArg[i]})
    if(data){
      updateRank(bla, bla, bla)
    }else{
      newRank(bla,bla,bla);
    }
  }
...
...
}