如何在node / loopback中同步调用model.find方法?

我正在使用自定义模型,并尝试使用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? } 

有没有办法同步调用查找方法? 请帮忙。

谢谢

所有这些模型方法(查询/更新数据)都是asynchronous的。 没有同步版本。 相反,您需要使用您传递的callback函数作为第二个参数:

 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包中的每个函数来解决这个问题。 例:

 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... } }); 

这样,你的代码是asynchronous的(迭代器funcions是同时执行的),除了callback函数,当所有完成时将被执行。

你的代码的例子是:

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