【问题标题】:how to make a block completely synchronous which consists of mongoose query?如何使由猫鼬查询组成的块完全同步?
【发布时间】:2017-11-26 15:04:14
【问题描述】:
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]) 
  }

}

因为组需要时间来查询猫鼬模式..所以当对象 [i] 进入组部分时,它显示未定义..我需要确保组的对象 [i] 执行并且控制应该转到 用户屏蔽

【问题讨论】:

  • 这就是“回调”和“承诺”的用途。您不能制作本质上是异步同步的东西。您必须等待它,并在它完成后做任何您需要做的事情。
  • 在 Javascript 中,您不能将异步操作变为同步操作。你就是不能。相反,您需要学习如何异步编程。您可以将代码嵌套到异步完成中,也可以使用承诺和链式操作。如果您向我们展示实际代码并使其成为一个真正的编码问题,而不仅仅是一个理论问题,我们可以为您提供更具体的帮助。 Stackoverflow 与您的实际代码配合得更好,我们可以向您展示解决问题的实际代码。我们不擅长在几段中教授一个一般性主题。
  • 另外,在for 循环内执行异步操作可能会导致问题,因为循环不会“等待”异步操作完成。同样,如果您向我们展示您想要实现的整体实际编码上下文,我们可以向您展示实际使其工作的代码。
  • 感谢 jfriend00 ..稍后会更新实际代码

标签: node.js asynchronous mongoose


【解决方案1】:

您可以使这个块同步,但只能在异步函数内部。你需要使用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 的浏览器中正确运行

【讨论】:

    猜你喜欢
    • 2016-11-19
    • 2023-04-08
    • 1970-01-01
    • 2017-12-13
    • 2023-03-07
    • 1970-01-01
    • 2018-08-09
    • 1970-01-01
    • 2014-05-12
    相关资源
    最近更新 更多