在循环里面使用回调函数赋值问题
发布于 9 年前 作者 chris9311 5176 次浏览 最后一次编辑是 8 年前 来自 问答

因为nodeJs的运行机制的原因,我要在循环里面使用回调函数函数赋值,因为是循环,所以我不能把传值的回调直接在循环里面使用回调函数,只能使用 if 语句在循环里面判断是否循环结束,结束则调用传值的回调函数;而我如果把传值的回调写在循环外面,则传过去一个[]空数组,只是nodeJS的EVENT LOOP是这样。。有没有其他写法可以在完成赋值之后再使用传值的回调。。谢谢大神

var stats = function(collections, cb) {
				  for (coll in collections) {
					  var collection = db.collection(collections[coll].name);
					  collection.stats(function(err,stats){ //赋值的回调函数
						  if(err){
							  res.render('error', {
								  message: err.message,
								  error: err
							  });
						 }
						  collections_stats.push({//赋值语句
							  name : stats.ns,
							  size : stats.size,
							  count : stats.count,
							  indexsize : stats.totalIndexSize
						  });
					  });
					  //if(coll == collections.length -1){//判断循环是否完成
					  //    cb(null,collections_stats);//使用回调函数把值传下去
					  //}
				  }
				  cb(null,collections_stats);//使用回调函数把值传下去
			  }
stats(collections_names,callback);
5 回复

@pfcoder 已经试过了waterfall,series了。那个赋值的回调还是最后再执行,传不出去

@chris9311 你用whilst试试

@chris9311 不知道你怎么写的,这是async的一个基本功能,见下面测试程序:

		var async = require('async');
		var collections = {
			a: {
				name: 'a'
			},
			b: {
				name: 'b'
			},
			c: {
				name: 'c'
			},
			d: {
				name: 'd'
			}
		};
	
	function delay_func(item, cb) {
		setTimeout(function() {
			console.log('time out');
			cb(null, item.name + '_performed')
		}, 100);
	}
	
	var finalResults = [];
	
	async.map(collections, function(item, callback) {
		console.log('collection name:' + item.name);
		delay_func(item, function(error, fakeResult) {
			console.log('delay func result:' + fakeResult);
			finalResults.push(fakeResult);
			callback(null, null);
		});
	}, function(err, results) {
    		console.log('final result:' + finalResults);
			// Your final callback should put here
	});
	```

@pfcoder 万分感谢。我对照了你的代码,发现我是callback()的位置写错了,谢谢指导

回到顶部