【发布时间】:2020-02-18 15:30:47
【问题描述】:
我有一个这样的数据集结构:
_id: SomeMongoID,
value: "a",
counter: 1
}
所以最初我的数据库表是空的。
现在我有一个数组,其中值如下:
const array = ["a", "a", "a"]
我最初想要的是我第一次进行搜索,所以它会清空结果,所以在这种情况下插入查询,现在下次它获取条目时,只需增加计数器。
为此,我编写了代码:
const testFunction = async(array) => {
try {
await Promise.all(
array.map(async x => {
const data = await CollectionName.findOne({value: x}).exec();
// Every time data will return null
if (data) {
//In this case only counter will have to increase
// But this block not run
} else {
//So by this first value will store
const value = new Value({
value: x,
counter: 1
});
await value.save()
}
})
)
} catch (error) {
console.log(error)
}
}
const array = ["a", "a", "a"]
testFunction(array);
问题是它会创建 3 个条目而不是单个条目。 map 函数不会等待,我使用 console.log() 通过手动调试检查。非常感谢任何帮助或建议。
【问题讨论】:
-
为什么要等待?你不是
awaiting 从你传递给map的函数返回的承诺,直到它们都开始并被包裹在Promise.all中 -
@Quentin 我更新了这个问题。这将创建 3 个条目而不是单个条目。
-
您可以执行
const dataArray = await Promise.all(array.map(x => CollectionName.findOne({value: x})),然后遍历该dataArray并执行您需要的任何操作。
标签: javascript node.js ecmascript-6 promise async-await