【问题标题】:NodeJS: map function will return an empty arrayNodeJS:map函数将返回一个空数组
【发布时间】:2020-04-09 13:57:07
【问题描述】:

我尝试使用 mssql npm 使用 mssql 数据库获取结果并将其推送到数组。似乎响应将在 map 函数之外返回一个空数组,非常感谢您的帮助,谢谢。

module.exports = {
 someRouteHandler: async function(req, res, next) {

  const fileStream = await readFileFromS3(req.body.filename); //a function to read file from AWS S3

  if (req.body.productName === "Nike" && type === "Male") {

   const result = await getBrandInformation(req.body, fileStream); //this function will parse data from the file and return object result
   const { brandInformation, brandItems } = result;
   const noneDuplicateArrayContainer = [];
   const duplicateArrayContainer = [];

   for ( const { itemNumber } of brandItems ) {

    let items = await getMatchingList(itemNumber); // will query to database if itemNumber has duplicate or none

    if (items.length > 1) {

     items.map(async({ identifier }) => {
      //if identifier not null query cost
      if (identifier) {
       let cost = await queryCostToDb(identifier); //will query cost from database
       duplicateArrayContainer.push({
        brandItems, identifier, cost
       })
      //if identifier is null no cost to save
      } else {
       duplicateArrayContainer.push({
        brandItems, identifier
       })
      }
     });
    //if items length is not greater than 1 meaning no duplicate
    } else {
     items.map(({ identifier }) => {
      let cost = await queryCostToDb(identifier); //will query cost from database
      noneDuplicateArrayContainer.push({
        brandItems, identifier, cost
       });
     })
    }
   }
   // when sending response noneDuplicateArrayContainer and duplicateArrayContainer  is [ ]
   // in the console, it has data, but response is delay
   return res.status(200).json({ brandInformation, noneDuplicateArrayContainer, duplicateArrayContainer })
  }
 }
}

【问题讨论】:

  • .map 是一个同步 API:它不会等待你的承诺:如果你检查 const x = items.mapx 将是一个承诺数组。你应该改用for await
  • 你好@ManuelSpigolon 我也尝试过使用await items.map,但它似乎仍然会返回空数组,感谢签入
  • 您不能在.map() 中使用await,但可以在for 循环中使用

标签: javascript node.js sql-server express


【解决方案1】:

我已经解决了这个问题,在我的代码中实现了await Promise.all,感谢大家的帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-23
    • 2019-10-31
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多