因此,我对JavaScript的承诺有一个问题。为了减少依赖关系,我使用本机实现。
是我需要的一个说明性的例子.
我需要找到书,书作者和购买的清单。我还需要为每个作者提供一个作者简介。在我得到所有这些之后,我需要为每一本书创建一组很好的作者,包括他们的书籍和购买清单。
列表和概要文件是单独的API JSON调用。唯一的依赖是,我需要一个作者列表才能获得作者配置文件。
我用承诺解决了这件事。我使用Promise.all获得3个API请求:作者、书籍和采购。我使用另一个Promise.all来获取我所得到的每个作者的所有配置文件(我循环遍历列表,映射每个配置文件的urls,并并行发送一批请求)。
一旦获得作者列表,我就运行配置文件请求批处理,从而在作者列表承诺的“然后”处理程序中运行。
Now,问题:
为了确保所有承诺、3个列表和所有配置文件都将在我组装库集之前完成,我需要在完成所有列表时,在第一个Promise.all然后处理程序中发送一批配置文件请求。
但是:一本书的购买清单要比作者名单花的时间长得多,我不想等待所有这些人发送一批个人资料请求,所以我把它发送到了作者列表承诺的处理程序中,所以只要我有了这些信息,这些就开始了。
但是,嵌套的Promise.all不包括它的父Promise.all然后处理程序,因此由于我的FinalFunction位于顶级Promise.all的那个时候,它可能(有时也会)在嵌套Promise.all完成检索完所有作者配置文件之前触发。
我需要能够尽快启动所有的承诺请求,但是只有一批作者请求取决于一个承诺是否完成才能开始,所以我需要等待那个承诺。所有其他的都应该独立地开始。
伪码
Promise.all(
requestBooks().then(){},
requestAuthors().then(){
GenerateArrayOfAuthorUris();
// now send a promisifyed batch of per-author requests
Promise.all(
[array of author uris to run requests for]
)
.then(){
// If I run this here, I may not have upper-level requests done
runCalculationsPerAuthorForAllAuthorsBooksPurchasesReceived();
}
},
requestPurchases().then(){},
)
.then(){
// this will fire when 3 top requests are done, but won't wait for
// the nested Promise.all with per-author requests
runCalculationsPerAuthorForAllAuthorsBooksPurchasesReceived();
}如果我这样做,我是在浪费宝贵的时间等待请求,我不需要等待仅仅是为了开始每个作者的请求:
Promise.all(
requestBooks().then(){},
requestAuthors().then(){
GenerateArrayOfAuthorUris();
},
requestPurchases().then(){},
)
.then(){
// now send a promisifyed batch of per-author requests
Promise.all(
[array of author uris to run requests for]
)
.then(){
// If I run this here, I may not have upper-level requests done
runCalculationsPerAuthorForAllAuthorsBooksPurchasesReceived();
}
}希望这能澄清我需要什么。
谢谢。
发布于 2016-04-11 14:02:14
正如评论中告诉您的那样,您没有从您的函数中获得任何return,因此then不知道需要等待什么内部承诺。
function getJokeCategories() {
return Promise.all([
// ^^^^^^
pgetJSON("http://api.icndb.com/categories"),
pgetJSON("http://api.icndb.com/jokes/count").then(function(data) {
var jokesToGet = [];
for (var i=0; i<data; i++){
jokesToGet.push("http://api.icndb.com/jokes/"+i);
}
return Promise.all(jokesToGet.map(function(jk) {
// ^^^^^^
return pgetJSON(jk).then(function(joke) {
// ^^^^^^
console.log(jk + " just returned", joke);
return joke;
// ^^^^^^
});
})).then(function(jokes) {
console.log("All jokes returned. This does happen only when all jokes are retrieved.");
return {count:data, jokes:jokes};
// ^^^^^^
});
})
]);
}
getJokeCategories().then(function(result) {
console.log(result, "This does happen at the very end when joke count, joke categories and all jokes are returned.");
});https://stackoverflow.com/questions/36545464
复制相似问题