async这个库里有什么方法可以把前面一个执行的结果传递到后面函数里直接用的吗?
发布于 6 年前 作者 tomoya92 2733 次浏览 来自 问答

我一般用的是

async.series({
	method1: function(next){
		next(null, 1);
	},
	method2: function(next) {
		next(null, 2);
	}
}, function(err, results) {
	console.log(results); // 结果是:{method1: 1, method2: 2}
});

现在有个问题,我在查询数据库的时候,method1里查询出来一个对象,然后要在method2方法里用到这个对象的一个变量,如果在不设置全局变量的情况下,async里有其它方法可以实现结果往下传递的吗?

23 回复

2018 年了,怎么还不用原生的 async,而是要用这个库

@atian25 呃,这个。。

假设现在是3年前,碰到这个问题呢 :joy

三年前也有 co 和 babel 了, [哭泣]

就 async 本身的话,不是有很多方法么,仔细看看文档吧,http://caolan.github.io/async/docs.html#compose 之类的

现在是2018年,你既然要改代码,完全可以用最新的async/await去重写一下

好吧, 我错了,听你们的,直接用 async/await :joy

async.auto({
    get_data: function(callback){
       mysql.query(sql,param,function(err,result){
	        callback(null,result); // 要传递的值
    	});
	},


	use_data: ['get_data', function(callback, results){
   	 let data = results.get_data;  // 接收到上面函数的值
    	callback(null,results);
	}]
}, function(err, results) {
	console.log('err = ', err);
	console.log('results = ', results);
});

@chinahsj 谢谢,我试试

我没记错的话,有个方法async.waterfall

来自酷炫的 CNodeMD

@atian25 我错了,我承认没有看这个链接 做了回伸手党 …

@MedusaLeee 是有这个方法

async.waterfall([
    function(callback) {
        callback(null, 'one', 'two');
    },
    function(arg1, arg2, callback) {
        // arg1 now equals 'one' and arg2 now equals 'two'
        callback(null, 'three');
    },
    function(arg1, callback) {
        // arg1 now equals 'three'
        callback(null, 'done');
    }
], function (err, result) {
    // result now equals 'done'
});

不过它有个不好的地方,就是上面返回参数都要在最后一个方法的 callback(null, arg1, arg2, ‘done’) 给写个,然后在最后才能收集到

compose(…functions)

Creates a function which is a composition of the passed asynchronous functions. Each function consumes the return value of the function that follows. Composing functions f(), g(), and h() would produce the result of f(g(h())), only this version uses callbacks to obtain the return values.

Each function is executed with the this binding of the composed function.

你这个可以用原生async/await解决。 async.js的定位和原生async/await语法还是不大一样的,async.js更突出的是流程控制,比如分批循环,取出100条数据执行完再取下100条数据这样的;而async/await只是异步操作的一种同步化写法而已。

@libook 听大伙的,昨天项目已经从express换成了koa 😂

来自 CNode-iOS

@tomoya92 既然都能换 Koa,为啥不直接上 Egg

@tomoya92 既然都能换 Koa,为啥不直接上 nest

@atian25 不是太喜欢egg

来自 CNode-iOS

@zhulinwei 不折腾了,koa够用了

来自 CNode-iOS

嗯,适合自己的就好

@tomoya92 其实async/await不一定非要换koa,只是个ES语法罢了,Express也可以用

@libook express里用的话,异常不好处理的。抛异常总是报错。

来自 CNode-iOS

回到顶部