[英]Call a Q promise function after promise chain invoked
我正在使用带有Q Promise库的Node.js应用程序。 我有两组承诺链,一组用于控制流程,另一组用于调用从中检索数据的服务方法。我的问题是,我需要将承诺链的返回值传递给我的其他承诺链。
MyExample.js
bookService.getBookById(bookId)
.then(bookDetals)
.then(function(returnValue) { // <- (A)
res.send(200, returnValue); // <- (C)
return returnValue;
}).catch(function(error) {
logger.error('Error getting values');
res.send(500, error);
});
bookDetals = function(book) {
myService.retrieveATypeData(book, bookId)
.then(function(bookData) {
myService.retrieveBTypeData(bookId)
.then(function(bdata) {
bookData[bTypeData] = bdata;
myService.retrieveCTypeData(bookId)
.then(function(cdata) {
bookData[cTypeData] = cdata;
}).done(function() {
return bookData; // <- (B)
})
});
});
};
在上面的代码中,我正在调用bookService.getBookById(bookId)并获取书。 然后我调用bookProtals函数,这是一个承诺链。 但是我的问题是,在诺言链结束之前,它会返回returnValue 。 我如何获得承诺链的返回值(在行(B)中)以返回到位(C)。 目前它返回之前。 因此,在C语言中,它表示未定义。
由于您正在使用Node,因此我将转向ES6 Promises。 如果您当前的版本尚不支持ES6 Promises,建议您切换到为您多填充的库( es6-promise )。 使用ES6,您可以执行以下操作:
// mock async promise
const getThing = id => (
new Promise((resolve, reject) => {
setTimeout(() => {
resolve({
id
});
}, 250);
})
);
// mock async promise
const getDetailsA = thing => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(Object.assign({}, thing, {
a: 'purple'
}));
}, 250);
})
};
// mock async promise
const getDetailsB = thing => (
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(Object.assign({}, thing, {
b: 'monkey'
}));
}, 250);
})
);
// mock async promise
const getDetailsC = thing => (
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(Object.assign({}, thing, {
c: 'dishwasher'
}));
}, 250);
})
);
getThing('123')
.then(getDetailsA)
.then(getDetailsB)
.then(getDetailsC)
.then(console.log)
.catch(console.error);
您需要返回一个承诺 :
bookDetals = function(book) {
return Q.Promise(function(resolve, reject, notify) {
myService.retrieveATypeData(book, bookId)
.then(function(bookData) {
myService.retrieveBTypeData(bookId)
.then(function(bdata) {
bookData[bTypeData] = bdata;
myService.retrieveCTypeData(bookId)
.then(function(cdata) {
bookData[cTypeData] = cdata;
}).done(function() {
resolve(bookData); // <- (B)
})
});
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.