如何在两个异步回调后运行某一个函数
发布于 8 年前 作者 zjy01 3907 次浏览 来自 问答

最近在尝试使用mongoose, 遇到了一些不好理解的地方 比如我有3个操作

getA(){}//从mongodb中获取A
getB(){}//从mongodb中获取B
count(){}// 对A和B操作

目前我是这样写的

getA(function(){
	getB(function(){
		count();
	})
});

就是A操作完后,回调操作B,然后操作count;但是,getA() 和 getB() 没有必然先后联系啊,把getB放在getA回调里会不会浪费时间;
能不能getA()、getB()分别执行,两个都执行完成后再触发执行count(),这该如何写,应不应该这样写? 求解答

4 回复

确保getA和getB返回的都是Promise 如果不是自己Promisify

Promise.all([getA(), getB()])
.spread(function(A, B){
	// operation here
})

觉得Promise方案好处还是多些

比较主流的是使用Async,如果是Promise风格,则可以使用Promise.all()

原理都是这样的:

var num = 0
var async = function(err) {
	if (++num === 2) {
		count()
	}
}
getA(async)
getB(async)
回到顶部