我一直在拼命尝试调用“ Feature
”模型,然后移动到(if(serviceExists===undefined))
行,如下所示,但无济于事。我以为async await
是行之有效的方法,但也无济于事。
我尝试将第一个if块放在Promise中,并将serviceExists
解析为Promise的变量,但这也不起作用。代码流只是等待Feature.query提取特征,然后继续执行第二个if块,即(if(serviceExists === undefined))
。
该块的执行取决于上一个。流量永远不会到达“基本”检查(即,如果在第1个外部if块中是第一个if块)。如何使它等待Feature模型的结果再执行?
let clientFeatures = await ClientFeature.query("clientId")
.eq(clientMongoId)
.exec();
if (clientFeatures.length > 0) {
var serviceExists;
clientFeatures.map(async item => {
let existingFeature = await Feature.queryOne("id")
.eq(item.featureId)
.exec();
let existingFeatureType = existingFeature.type;
if (
existingFeatureType === "base" &&
reSelectedFeatureType === "base"
) {
existingBaseFeatureId = existingFeature.id;
if (existingBaseFeatureId === reSelectedFeature[0].id) {
serviceExists = true;
}
}
});
}
if (serviceExists === undefined) {
var clientFeatureGen = await ClientFeature.create({
id: uuidv1(),
clientId: clientMongoId,
featureId: featureMongoId
});
}
答案 0 :(得分:2)
由于您在map
中使用异步函数,因此应“等待”它使用Promise.all
创建的所有诺言
有关详细信息和CodePen示例,请参见此post。
从CodePen中获取的代码:
const arr = [ { key: 1 }, { key: 2 }, { key: 3 } ]
const results = arr.map(async (obj) => { return obj.key; });
Promise.all(results).then((completed) => document.writeln( `\nResult: ${completed}`));