猫鼬异步承诺似乎不起作用
Mongoose async promise don't seem to work
我在将 async' 与 mongoose 一起使用时遇到了一些麻烦。基本上我的代码如下:
function() {
SchemaOne.findById(fooIdOne).exec().then( x => {
// Some first instructions
myCollection.foreach( y => {
SchemaTwo.findById(fooIdTwo).exec().then( z => {
// Some second instructions
});
});
}).then(() => {
// Code to execute after
});
}
这里我希望在“之后执行的代码”之前执行“第一条指令”和“第二条指令”,但最后的“然后”似乎没有等待第二条指令的执行.
需要一点帮助!
非常感谢 !凯夫'.
您的 forEach
调用是同步执行的,您没有 return then
回调中的承诺。
您应该收集在循环中创建的承诺,并且 return Promise.all
个。
function() {
SchemaOne.findById(fooIdOne).exec().then( x => {
// Some first instructions
let promises = [];
myCollection.foreach( y => {
promises.push(SchemaTwo.findById(fooIdTwo).exec().then( z => {
// Some second instructions
}));
});
return Promise.all(promises);
}).then(() => {
// Code to execute after
});
}
我在将 async' 与 mongoose 一起使用时遇到了一些麻烦。基本上我的代码如下:
function() {
SchemaOne.findById(fooIdOne).exec().then( x => {
// Some first instructions
myCollection.foreach( y => {
SchemaTwo.findById(fooIdTwo).exec().then( z => {
// Some second instructions
});
});
}).then(() => {
// Code to execute after
});
}
这里我希望在“之后执行的代码”之前执行“第一条指令”和“第二条指令”,但最后的“然后”似乎没有等待第二条指令的执行.
需要一点帮助! 非常感谢 !凯夫'.
您的 forEach
调用是同步执行的,您没有 return then
回调中的承诺。
您应该收集在循环中创建的承诺,并且 return Promise.all
个。
function() {
SchemaOne.findById(fooIdOne).exec().then( x => {
// Some first instructions
let promises = [];
myCollection.foreach( y => {
promises.push(SchemaTwo.findById(fooIdTwo).exec().then( z => {
// Some second instructions
}));
});
return Promise.all(promises);
}).then(() => {
// Code to execute after
});
}