javascript - 如何在for循环中等待每次迭代并返回响应作为nodeJS中的API响应

标签 javascript node.js asynchronous nodes node-modules

我使用 for 循环来迭代元素数组,并在 for 循环内使用不同的参数调用相同的函数。这是我的代码:

exports.listTopSongs = function(query) {
    return new Promise(function(resolve, reject) {
        var str = query.split(","), category,
        for(var i=0; i<str.length; i++) {
           sampleFn(str[i], 'sample', resolve, reject);
        }
    });
};

function sampleFn(lang, cat, resolve, reject) {
        client.on("error", function (err) {
            console.log(err);
            var err = new Error('Exception in redis client connection')
            reject(err);                                
        });
        client.keys(lang, function (err, keys){
            if (err) return console.log(err);
            if(keys.length != 0) {
                client.hgetall(keys, function (error, value) {
                    var objects = Object.keys(value);
                    result['title'] = lang;
                    result[cat] = [];
                    var x =0;
                    for(x; x<objects.length; x++) {
                        var val = objects[x];
                            User.findAll({attributes: ['X', 'Y', 'Z'],
                                where: {
                                    A: val
                                }
                            }).then(data => {
                                if(data != null) {
                                    //some actions with data and stored it seperately in a Json array
                                    if(result[cat].length == objects.length) {
                                        resolve(result);
                                    }
                                } else {
                                    console.log(""+cat+" is not avilable for this value "+data.dataValues['X']);
                                }
                            });
                    }
               });
         });
   }

这里它不会等待第一次迭代完成。它只是在完成第一次迭代功能之前异步运行。我需要将结果返回为 result:[{ 1, 2}, {3,4}]。但它运行无缝,并在完成所有对象之前返回空对象或仅返回一个对象。如何解决。

我使用了 Node 异步循环。但它使用 next 并且我无法在使用该包时发送我的参数。请帮助我

最佳答案

Async提供允许这样做的控制流方法。

使用async.each :

async.each(openFiles, function(file, callback) {

    // Perform operation on file here.
    console.log('Processing file ' + file);

    if( file.length > 32 ) {
      console.log('This file name is too long');
      callback('File name too long');
    } else {
      // Do work to process file here
      console.log('File processed');
      callback();
    }
}, function(err) {
    // if any of the file processing produced an error, err would equal that error
    if( err ) {
      // One of the iterations produced an error.
      // All processing will now stop.
      console.log('A file failed to process');
    } else {
      console.log('All files have been processed successfully');
    }
});

关于javascript - 如何在for循环中等待每次迭代并返回响应作为nodeJS中的API响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46294069/

相关文章:

java - 使用 CompletableFuture 从主线程退出

javascript - Aurelia 获取客户端中的 "Unhandled rejection"错误

javascript - Slick.js 不适用于 Polymer 2.0

mysql - 每当数据库字段发生变化时将数据推送到客户端

python - 异步: terminating all tasks when one of them throws exception

c# - 如何查明 WebClient.DownloadFileTaskAsync 是否已取消?

javascript - Hello World 在 react 中不起作用

javascript - 如何访问我的 Controller 中的 AngularJS ui-bootstrap datepicker 值

javascript - Socket.io动态 "on"绑定(bind)

mysql - Nodejs,mysql {[错误: connection lost: the server closed the connection.]