如何在节点/环回中同步调用 model.find 方法

How to call model.find method synchronously in node / loopback?

本文关键字:调用 同步 model find 方法 节点      更新时间:2023-09-26

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