【问题标题】:Store data in an array using for each in node js sequelize使用for each in node js sequelize将数据存储在数组中
【发布时间】:2020-12-09 14:30:30
【问题描述】:

我正在尝试使用 foreach 将获取的数据推送到数组中,但它只返回循环中的第一个数据。这是我的代码。

exports.getAllTrial = async function (req, res, next) {

try {
    
    new Promise( async (resolve, reject) => {
        var reservations = [];
        await Schedule.getSchedule()
        .then(data => {
            data.forEach(async (element) => { 
                await saveReserve.getAllTrial({where: {scheduleID: element.id, date: "8/18/2020"}})
                .then(trial => {
                    trial.forEach(response => { 
                        reservations.push(response.scheduleID)
                    })
                }) 
                console.log(reservations);
                resolve(reservations);
            })
        });
    })

    .then(value=>{
        res.status(200).json(value);
    })
    .catch(err => {
        console.log(err);
    });

} catch (e) {
    return res.status(400).json({ status: 400, message: e.message });
}

}

我的预期输出应该是:[ 9, 10, 10 ] 但它只返回 [9]。

【问题讨论】:

    标签: node.js arrays foreach sequelize.js


    【解决方案1】:

    foreach 循环中的异步代码是个坏主意,因为它不会一个接一个地执行。我建议阅读更多 async/await 和 promise 的概念,因为您在这里混合了一些东西(例如混合 await.then)。还值得研究Promise.all,它将解决一系列承诺和array.map

    虽然我不知道某些变量(例如 saveReserve)应该是什么或做什么,但您的代码可能会简化为:

    exports.getAllTrial = async (req, res, next) => {
      try {
        const data = await Schedule.getSchedule()
    
        const reservations = await Promise.all(
          data.map(element => {
            return saveReserve.getAllTrial({ where: { scheduleID: element.id, date: '8/18/2020' } })
          })
        )
    
        return res.status(200).json(reservations)
      } catch (e) {
        return res.status(400).json({ status: 400, message: e.message })
      }
    }
    

    【讨论】:

    • 非常感谢。有效。是的,我会更多地了解它。 :)
    • 如何在 data.map 中推送一个数组,因为我必须从 getSchedule 获取数据并使用从 getAllTrial 获取的数据推送
    • 保留变量将包含所有 getAll 调用的结果,data 包含 getSchedule 的结果。如果 data 是一个数组,那么您可以使用 .concat 来获得一个包含两者内容的最终数组。在同一个数组中有不同类型的数据听起来很奇怪?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-18
    • 2017-10-07
    • 2023-03-06
    • 1970-01-01
    • 2017-11-09
    • 2011-10-31
    • 2018-08-07
    相关资源
    最近更新 更多