如何使包含猫鼬查询的块完全同步? [英] how to make a block completely synchronous which consists of mongoose query?

查看:50
本文介绍了如何使包含猫鼬查询的块完全同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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]) 
  }

}

由于组花时间查询猫鼬模式,所以当object [i]进入组部分时,它显示为undefined..i需要确保组的object [i]执行并且控件应转到 用户封锁

since group is taking time for querying mongoose schema..so when the objects[i] comes to group section it shows undefined..i need to make sure objects[i] for group executes and the control should go to user block

推荐答案

您可以使此块同步,但只能在异步函数内部.您需要使用async/await就是这样.

You can make this block sync but only inside of async function. You need to use async/await and thats all.

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

This example will run correctly in Node.js 8+ and browsers supporting async/await

这篇关于如何使包含猫鼬查询的块完全同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆