【问题标题】:how can i execute mysql insert statement synchronously inside javascript map我如何在javascript map中同步执行mysql insert语句
【发布时间】:2021-03-05 17:20:15
【问题描述】:

我想在数组中插入行并对结果做一些事情,但似乎一切都是异步执行的。这是我的代码。我希望 console.log 有值但每次都是空的,似乎我无法让我的代码以同步方式执行它

    const resultMap = []
    const result = await anArray.map(async (o) => {
        const result = await connection.query('insert into (...) values (...)', [...]);
        resultMap.push(result);
        console.log('----> pushed', )
    });

    console.log(resultMap);

输出:

    []
    ----> pushed
    ----> pushed
    ----> pushed
    ----> pushed
    ----> pushed
    ----> pushed
    ----> pushed

【问题讨论】:

  • 我们可以这样做,但异步进行更容易。因为您必须在服务器完成任务时停止所有活动,这应该是很好的考虑
  • 好吧,我不是在寻找更简单的解决方案,因为我正在尝试解决问题,我需要在继续之前拥有所有插入的 ID
  • 有一些关于这个句柄的教程,像这样medium.com/@patarkf/…
  • 该示例展示了如何重写代码,您需要仔细阅读它,因为它表明您必须重写很多 miore 1one 函数。
  • 问题是异步等待在 javascript 地图中不起作用,本教程向您展示了如何使用异步等待

标签: javascript mysql node.js async-await


【解决方案1】:

带有异步的地图返回一个你必须解决的承诺数组。

function asyncTask (arg){
    return new Promise((resolve)=>{resolve (arg)})
}


const resultMap = []
async function test (){
    const result = await Promise.all([1,2,3].map(async (item) => {
        const result = await asyncTask(item);
        resultMap.push(result);
        console.log('----> pushed', item)
    }));
    console.log(resultMap)
}

test()

【讨论】:

    猜你喜欢
    • 2010-11-13
    • 1970-01-01
    • 2016-09-11
    • 2019-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-15
    相关资源
    最近更新 更多