我正在使用诺言库Bluebird,我目前遇到的问题是函数内部的所有内容都运行良好,但是当我尝试返回一个值时,函数会返回undefined
。
这是承诺链:
function foo() {
createGroupMembers(parsedChat).then(function(val) {
var members = val;
createMessages(parsedChat, maxPages).then(function(val) {
var messages = val;
Promise.all([ createFrontCover(subject, firstdateOfMessages, lastDateOfMessages, isPreview), createStats(parsedChat), createBackCover(parsedChat)])
.then(function (results) {
var front = results[0];
var stats = results[1];
var backcover = results[2];
var book = head + front + stats + members + messages + backcover;
console.log('pages in this book: ', pages);
console.log(book); // logs perfect values.
return book;
});
});
});
}
问题很简单:在致电foo()
时,它的值变为undefined
而不是预订。为什么我会遇到这种行为?
答案 0 :(得分:21)
function foo() {
return createGroupMembers(parsedChat).then(function(val) {
var members = val;
return createMessages(parsedChat, maxPages).then(function(val) {
var messages = val;
return Promise.all([createFrontCover(subject, firstdateOfMessages, lastDateOfMessages, isPreview), createStats(parsedChat), createBackCover(parsedChat)])
.then(function(results) {
var front = results[0];
var stats = results[1];
var backcover = results[2];
var book = head + front + stats + members + messages + backcover;
console.log('pages in this book: ', pages);
console.log(book); // logs perfect values.
return book;
});
});
});
}
现在foo将返回一个可以解析为book
值的promisefoo().then(function(book) {
console.log('huzzah I have book ' + book);
});
说实话,foo
可以改写,但这完全是另一个问题
仅供参考:你可以为foo做这样的事情
function foo() {
return createGroupMembers(parsedChat)
.then(function(members) { // members
return Promise.all([members, createMessages(parsedChat, maxPages)]);
})
.then(function(members_messages) { // membersMessages
return Promise.all([createFrontCover(subject, firstdateOfMessages, lastDateOfMessages, isPreview), createStats(parsedChat)].concat(members_messages, [createBackCover(parsedChat)]));
})
.then(function(results) { // front, stats, members, messages, back
var book = head + results.join('');
console.log('pages in this book: ', pages);
console.log(book); // logs perfect values.
return book;
});
}
在第二个(是你唯一的)Promise.all中添加了顺序,并在其中添加了先前的Promise结果,使部件的最终连接像.join
一样简单 - 这样做会这样做也正确地传播任何错误,所以你对foo的使用可以是
foo().then(function(book) {
console.log('huzzah I have book ' + book);
}).catch(function(err) {
// handle any and all errors here
});