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

Raj*_*ani 5 javascript rest node.js strongloop loopbackjs

我正在使用自定义模型并尝试使用find方法在循环中过滤它.例如,如下所示

for i = 0 to n
{
var u = User.find( where { name: 'john'});
}
Run Code Online (Sandbox Code Playgroud)

它不起作用.

另外,如果我使用以下内容

for i = 0 to n
{
User.find( where { name: 'john'}, function(u) {... } );

// How do I call the code for further processing? 
}
Run Code Online (Sandbox Code Playgroud)

有没有办法同步调用find方法?请帮忙.

谢谢

jak*_*lla 1

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

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') { ... }
    } );
}
Run Code Online (Sandbox Code Playgroud)