CNode

请问怎样使用promise同时读取数据库的3个表~~

问答
7735254599发布于11 年前最后回复11 年前20 回复7247 浏览0 收藏

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

A.find().then()..... .......

查看回复

回复 (20)

L
luoyjx#1·11 年前

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

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

})
.catch(function() { });
7
735254599#2·11 年前
L
luoyjx#4·11 年前
引用 735254599@luoyjx A B C都是数据库的表

@735254599 我只是举例方法ABC

7
735254599#5·11 年前
引用 luoyjx@735254599 我只是举例方法ABC

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

L
luoyjx#6·11 年前

new 个Promise包住

V
VectorHo#7·11 年前

参考mongoose的Population

Y
ysj16#8·11 年前
引用 luoyjx同步啊,看错了,刚写了个异步,删了。。 如果A已经promise化了的话

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

H
hacke2#9·11 年前
引用 ysj16@luoyjx 有个问题,在c的那个then中,怎样获取a里面取得的数据

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

resolve({
	a : a
})

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

L
luoyjx#10·11 年前
引用 ysj16@luoyjx 有个问题,在c的那个then中,怎样获取a里面取得的数据

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

Y
ysj16#11·11 年前
引用 luoyjx@ysj16 你可以保存在外面,或者再用个Promise.resolve()往下传递也行

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

H
hacke2#12·11 年前
引用 ysj16@luoyjx @hacke2 传递下去了怎么取到这个值呢

@ysj16 直接是函数的参数啊

L
luoyjx#13·11 年前
.then(function(b_result) {
	return Promise.all([
		Promise.resolve(b_result),
		C.find()
	]);
})
.spread(function(b_result, c_result) {

})
S
sunjie20081001#14·11 年前

不错的客户端

Y
ysj16#15·11 年前

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

Y
ysj16#16·11 年前

@luoyjx @hacke2 初学见笑了。。

L
luoyjx#17·11 年前
引用 ysj16@luoyjx @hacke2 A .find() .then(function(a){ console.log(a) return B.find() }) .then(function(){...

@ysj16

A
.find()
.then(function(a){
	console.log(a); 
	return Promise.all([
		B.find(),
		Promise.resolve(a);
	]);
})
.spread(function(b, a){
	console.log(arguments)
})
Y
ysj16#18·11 年前
引用 luoyjx@ysj16

@luoyjx @hacke2 多谢解惑=3=

H
hacke2#19·11 年前
引用 ysj16@luoyjx @hacke2 多谢解惑=3=

@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
}

这种方式多优雅

W
wyTrivail#20·11 年前

async

参与回复
登录后即可参与回复。登录