如何在节点/环回中同步调用 model.find 方法
How to call model.find method synchronously in node / loopback?
我正在使用自定义模型并尝试使用 find 方法在循环中过滤它。
for i = 0 to n
{
var u = User.find( where { name: 'john'});
}
它不起作用。
另外,如果我使用以下
for i = 0 to n
{
User.find( where { name: 'john'}, function(u) {... } );
// How do I call the code for further processing?
}
有没有办法同步调用查找方法?请帮忙。
谢谢
您可以使用异步包中的 each 函数解决此问题。例:
async.each(elements, function(element, callback) {
// - Iterator function: This code will be executed for each element -
// If there's an error execute the callback with a parameter
if(error)
{
callback('there is an error');
return;
}
// If the process is ok, execute the callback without any parameter
callback();
}, function(err) {
// - Callback: this code will be executed when all iterator functions have finished or an error occurs
if(err)
console.log("show error");
else {
// Your code continues here...
}
});
这样,您的代码是异步的(迭代器功能同时执行),除了将在所有操作完成后执行的回调函数。
您的代码示例为:
var elements = [1 .. n];
async.each(elements, function(element, callback) {
User.find( where { name: 'john'}, function(u) {
if(err)
{
callback(err);
return;
}
// Do things ...
callback();
});
}, function(err) {
if(err)
console.log("show error");
else {
// continue processing
}
});
所有这些
模型方法(查询/更新数据)都是异步的。没有同步版本。相反,您需要使用作为第二个参数传递的回调函数:
for (var i = 0; i<n; ++i) {
User.find( {where: { name: 'john'} }, function(err, users) {
// check for errors first...
if (err) {
// handle the error somehow...
return;
}
// this is where you do any further processing...
// for example:
if (users[0].lastName === 'smith') { ... }
} );
}
async myFunction(){
for(var i = 0; i < n; i++) {
var u = await User.find( {where { name: 'john'}});
}
}
相关文章:
- 同步调用,直到用户通过angular验证为访问者
- ajax调用获胜't同步执行
- 如何模拟同步ajax调用?(基于异步的同步)
- 同步(阻塞)ajax调用是否可以阻塞浏览器'的UI
- 如何使用javascript中的生成器模拟同步调用
- 使用模态库从嵌套的异步调用中生成javascript同步代码
- node.js,async,restify:无法使restify调用在async.series内同步
- 使用同步ajax调用加载屏幕
- 在 Javascript 中调用是同步的
- 异步函数调用是否可以在两个同步语句之间完成
- 使Javascript调用同步
- 如何使 Nodejs 调用同步,然后我可以轻松使用它
- 如何在 Node.js 中强制调用同步
- 如何(真的!)使JavaScript异步调用同步(在Chrome上)
- 从外部JS文件调用同步函数
- Javascript/jQuery ajax调用同步的常用实践
- jQuery ajax调用同步vs异步
- 应该由Promise调用同步代码.然后创建一个新的Promise
- 什么'是在使用Flux时保持UI与ajax调用同步的惯用方法
- 无法在javascript中调用同步函数