for(var i = 0 ; i < objects.length ; i++){
if(type == "user")
{ // normal mathematical calculations
// result.push(objects[i])
}
else if( type == "group"){
// Here i need a query "group" model
// find group related stuffs
// and then push to result
// result.push(objects[i])
}
}
因为组需要时间来查询mongoose模式..所以当对象[i]来到组部分时它显示未定义..我需要确保组的对象[i]执行并且控件应该去 用户块
答案 0 :(得分:0)
您可以进行此块同步,但仅限于异步功能。您需要使用async
/ await
,这就是全部。
async function syncBlock(objects) {
const result = [];
for (var i = 0; i < objects.length; i++) {
const type = objects[i].type;
if (type === "user") {
result.push(objects[i])
} else if (type === "group") {
// Now loop will "wait" for result from find
const res = await find(objects[i]);
result.push(res)
}
}
return result;
}
async function find(o) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(o);
}, 100);
});
}
syncBlock([
{type : 'group'},
{type : 'user'},
{type : 'group'},
{type : 'user'},
{type : 'group'}
]).then((res) => {
console.log(res);
}).catch((err) => {
console.error(err);
});
此示例将在Node.js 8+和支持async
/ await
的浏览器中正确运行