请问怎样使用promise同时读取数据库的3个表~~
发布于 9 年前 作者 735254599 5790 次浏览 最后一次编辑是 8 年前 来自 问答

数据库是mongo 有A,B,C,三个collections,我需要使用promise同步读取这三个合集的数据。。。看了官方文档看不懂啊,求大神来个例子~~

A.find().then()… …

20 回复

同步啊,看错了,刚写了个异步,删了。。 如果A已经promise化了的话

A()
.then(function() {
	return B();
})
.then(function() {
	return C();
})
.then(function() {

})
.catch(function() { });

@luoyjx 我就是不知道B()里面的细节,晕~~~~

@luoyjx A B C都是数据库的表~~

@735254599 我只是举例方法ABC

@luoyjx 那请问B函数里面具体怎么实现的~~~

new 个Promise包住

参考mongoose的Population

@luoyjx 有个问题,在c的那个then中,怎样获取a里面取得的数据

@ysj16 @luoyjx 说的对,返回一个Promise对象,第二个问题我的做法是在resolve里传递的不是查出来的值,而是传递一个对象,里面f赋予值,如:

resolve({
	a : a
})

如果c想用b和a,那么都赋予这个对象,这样应该不是很好的解决方案,求高手指点

@ysj16 你可以保存在外面,或者再用个Promise.resolve()往下传递也行

@luoyjx @hacke2 传递下去了怎么取到这个值呢

@ysj16 直接是函数的参数啊

.then(function(b_result) {
	return Promise.all([
		Promise.resolve(b_result),
		C.find()
	]);
})
.spread(function(b_result, c_result) {

})

不错的客户端

@luoyjx @hacke2 A .find() .then(function(a){ console.log(a) return B.find() }) .then(function(){ console.log(arguments) }) 就像这样,第二个console里面想拿到a

@luoyjx @hacke2 初学见笑了。。

@ysj16

A
.find()
.then(function(a){
	console.log(a); 
	return Promise.all([
		B.find(),
		Promise.resolve(a);
	]);
})
.spread(function(b, a){
	console.log(arguments)
})

@ysj16

function getExample() {
    return promiseA(…)
    .bind({}) // Bluebird only!
    .then(function(resultA) {
        this.resultA = resultA;
        // some processing
        return promiseB(…);
    }).then(function(resultB) {
        // more processing
        return // something using both this.resultA and resultB
    }).bind(); // don't forget to unbind the object if you don't want the
               // caller to access it
}

这种方式多优雅

回到顶部