简体   繁体   English

异步函数在 map function 内没有以正确的顺序执行

[英]async functions not executing in the correct order inside a map function

I have created an async function that will extra the data from the argument, create a Postgres query based on a data, then did some processing using the retrieved query data.我创建了一个异步 function 将从参数中提取数据,基于数据创建 Postgres 查询,然后使用检索到的查询数据进行一些处理。 Yet, when I call this function inside a map function, it seemed like it has looped through all the element to extra the data from the argument first before it proceed to the second and the third part, which lead to wrong computation on the second element and onwards(the first element is always correct).然而,当我在 map function 中调用此 function 时,似乎它已经遍历了所有元素以在第二个元素上额外的数据,这导致了第二个元素的错误计算,然后第三个元素继续执行及以后(第一个元素总是正确的)。 I am new to async function, can someone please take at the below code?我是异步 function 的新手,有人可以看看下面的代码吗? Thanks!谢谢!

async function testWeightedScore(test, examData) {
    var grade = [];
    const testID = examData[test.name];
    console.log(testID);
    var res = await DefaultPostgresPool().query(
         //postgres query based on the score constant
        );
    var result = res.rows;
    for (var i = 0; i < result.length; i++) {
        const score = result[i].score;
        var weightScore = score * 20;
        //more computation
        const mid = { "testID": testID, "score": weightScore, more values...}; 
        grade.push(mid);
    }
    return grade;
}

(async () => {
    const examSession = [{"name": "Sally"},{"name": "Bob"},{"name": "Steph"}]
    const examData = {
        "Sally": 384258,
        "Bob": 718239,
        "Steph": 349285,
    };
    var test = [];

    examSession.map(async sesion => {
        var result = await testWeightedScore(sesion,examData); 
        let counts = result.reduce((prev, curr) => {
            let count = prev.get(curr.testID) || 0;
            prev.set(curr.testID, curr.score + count);
            return prev;
          }, new Map());
        let reducedObjArr = [...counts].map(([testID, score]) => {
            return {testID, score}
        })      
        console.info(reducedObjArr);
    }
    );
})();

// The console log printed out all the tokenID first(loop through all the element in examSession ), before it printed out reducedObjArr for each element

The async/await behaviour is that the code pause at await, and do something else (async) until the result of await is provided. async/await 行为是代码在 await 处暂停,然后执行其他操作(异步),直到提供 await 的结果。

So your code will launch a testWeightedScore , leave at the postgresql query (second await ) and in the meantime go to the other entries in your map , log the id, then leave again at the query level.因此,您的代码将启动testWeightedScore ,留在 postgresql 查询(第二次await ),同时 go 到您的map中的其他条目,然后再次登录查询级别。 I didn't read your function in detail however so I am unsure if your function is properly isolated or the order and completion of each call is important.我没有详细阅读您的 function 但是,所以我不确定您的 function 是否已正确隔离,或者每个呼叫的顺序和完成是否很重要。

If you want each test to be fully done one after the other and not in 'parallel', you should do a for loop instead of a map .如果您希望每个测试一个接一个地完成而不是“并行”,您应该执行for循环而不是map

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM