最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

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

IT培训 admin 11浏览 0评论

如何在节点/环回中同步调用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? 
}

是否有一种方法可以同步调用find方法?请帮助。

谢谢

回答如下:

您可以使用async package中的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
    }

});

如何在节点/环回中同步调用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? 
}

是否有一种方法可以同步调用find方法?请帮助。

谢谢

回答如下:

您可以使用async package中的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
    }

});
发布评论

评论列表 (0)

  1. 暂无评论