async这个库里有什么方法可以把前面一个执行的结果传递到后面函数里直接用的吗?
我一般用的是
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 回复
三年前也有 co 和 babel 了, [哭泣]
就 async 本身的话,不是有很多方法么,仔细看看文档吧,http://caolan.github.io/async/docs.html#compose 之类的
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);
});@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只是异步操作的一种同步化写法而已。