我使用 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/