【发布时间】: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.map,x将是一个承诺数组。你应该改用for await -
你好@ManuelSpigolon 我也尝试过使用
await items.map,但它似乎仍然会返回空数组,感谢签入 -
您不能在
.map()中使用await,但可以在for循环中使用
标签: javascript node.js sql-server express