简体   繁体   English

当 for 中有查询时如何返回异步 function 的值

[英]How to return a value of an async function when there's a query inside a for

I'm trying to return a value after a for loop has been completed, the for loop is inside an async function.我试图在 for 循环完成后返回一个值,for 循环位于异步 function 内。 Inside the loop, there's a query that inserts to the db.在循环内部,有一个插入到数据库的查询。

The function is working ok, but when i use postman, the response returns empty (even tho the values have been inserted to the db) function 工作正常,但是当我使用 postman 时,响应返回空(即使值已插入数据库)

Here's how i call the function:以下是我如何称呼 function:

        insertarPracticas(turno_id,req.body.lista_codigos_practicas, queryInsertarPracticas)
        .then( result=> {
                 res.status(200).json({
                      "Practicas Agregadas": result
                    })
                 }
        )

And here's the function:这是 function:

async function insertarPracticas(turno_id, req, queryInsertarPracticas){
//practicasAgregadas="";
return new Promise((resolve, reject) => {
    for (let i=0; i< req.length; i++){ 
        connection.query(
            queryInsertarPracticas, [turno_id, req[i]],(error2, row2) => { 
                if (error2) {
                    console.log("Error al insertar turno detalle (prácticas): "+req[i] +" "+ error2);             
                    practicasNoAgregadas += req[i] + "-";                   
                }else{
                    console.log("Turnos detalle agregados "+req[i]);
                    practicasAgregadas += req[i] + "-"; 
                    console.log("practicas "+practicasAgregadas);
                }
        });
        console.log("en for "+practicasAgregadas);
    }
    resolve(practicasAgregadas)

    // Or of there was an error
    reject("error");
})

What's happening here is that the function won't wait for the connection query to end, even tho it inserts values to the db, on Postman i get the first result, which is empty:这里发生的事情是 function 不会等待连接查询结束,即使它向数据库插入值,在 Postman 上我得到第一个结果,它是空的:

在此处输入图像描述

But i do have the values inserted on my database.但我确实在我的数据库中插入了值。

What's the correct way to handle this?处理这个问题的正确方法是什么? I've tried using map instead of for, and now i'm trying with promise, but i'm not sure i'm using it correctly.我尝试使用 map 而不是 for,现在我正在尝试使用 promise,但我不确定我是否正确使用它。

Here's the console, where you can see that the console.log("en for" + practicasAgregadas) returns empty, when it should have some values.这是控制台,您可以在其中看到 console.log("en for" + practicasAgregadas) 返回空,但它应该有一些值。

after your map, just use:在您的 map 之后,只需使用:

await Promise.all(yourArray);等待 Promise.all(yourArray);

I don't know how you built your connection file, but you should change it to an async function and await the connection.query我不知道您是如何构建连接文件的,但您应该将其更改为异步 function 并等待 connection.query

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

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