嵌套承诺会产生类似的效果
Nesting promises for a parallel effect?
我不得不在承诺中嵌套一个承诺,这可以吗,还是被认为是糟糕的做法?
- 我有一个类,它有一个方法
fetchArticles
、fetchImages
和main
。main
是调用fetchArticles
+fetchImages
的fetchArticles
从另一个文件中运行一个函数,该函数返回promise,但我也在fetchArticles
类方法本身上返回promise。因此,当它获取文章时,它将继续获取图像fetchImages
方法未被承诺,而是从另一个文件中调用一个承诺的函数
我不确定这是否是实现鹦鹉学舌效果的最佳方式?
main () {
// Call the promised fetchArticles class method
this.fetchArticles()
.then ( () => this.fetchImages( () => {
this.res.json(this.articles.data);
}));
}
fetchArticles () {
return new Promise ((fullfil, rej) => {
// Calling a promised function which simply returns an array of articles
fetchArticles (this.parametersForApiCall)
.then ( (data) => {
this.articles.data = data;
this.articles.imageIds = [1,5,2,8,99,1000,22,44,55,120,241]; // Extract image IDS and save to class this
fullfil();
})
.catch ( (err) => {
console.log ("Something went wrong with api call", err);
res.json({error: "Something went wrong", code: 1011});
reject();
});
});
}
fetchImages (cb) {
// Calling a promised function which simply returns an array of images
fetchImages (this.imageIds).then( (imgs) => {
this.images = imgs;
cb (); // Temp callback method
}).catch ( (err) => {
console.log (err, "error finding images in then")
})
}
}
我应该使用异步并行之类的东西吗?注意,我在fetchImages
方法中临时添加了一个callback
,直到找到一个很好的链接承诺的解决方案。
几个注意事项:
-
您在
fetchArticles
函数中创建了一个不必要的承诺。您可以直接返回承诺的fetchArticles的结果。 -
使用Promise.all可以让你同时发射两个项目。如果你的两种方法不相互依赖,那么这是一个很好的方法。我已经用那个代码更新了
main
函数。 -
类似地,您可以直接在
fetchImages
函数中返回promise。因为这也是承诺的,所以您不再需要回调。我把它拿走了。
生成的代码
main () {
// Call the promised fetchArticles and fetchImages class methods
Promise.all([this.fetchArticles(), this.fetchImages()])
.then(() => this.res.json(this.articles.data));
}
fetchArticles () {
// Calling a promised function which simply returns an array of articles
return fetchArticles (this.parametersForApiCall)
.then ( (data) => {
this.articles.data = data;
this.articles.imageIds = [1,5,2,8,99,1000,22,44,55,120,241]; // Extract image IDS and save to class this
})
.catch ( (err) => {
console.log ("Something went wrong with api call", err);
res.json({error: "Something went wrong", code: 1011});
reject();
});
}
fetchImages () {
// Calling a promised function which simply returns an array of images
return fetchImages (this.imageIds).then( (imgs) => {
this.images = imgs;
}).catch ( (err) => {
console.log (err, "error finding images in then")
})
}
}
似乎是Promise.all
的工作。
相关文章:
- 嵌套承诺会产生类似的效果
- 如何将嵌套设置超时转换为承诺
- 干净的代码和嵌套的承诺
- 蓝鸟承诺 - 嵌套与拒绝模式
- 如何展平嵌套承诺依赖项
- 余烬嵌套的路线和承诺
- 嵌套承诺
- 测试嵌套AngularJS与Jasmine的承诺
- 转换嵌套'对于'循环成一个承诺,为了一个承诺?嵌套承诺
- 嵌套承诺与q-io
- 如何将嵌套承诺与Q连锁?我可以'Don’我不能让它们按正确的顺序运行
- 在嵌套承诺链中重新引发异常
- 此代码中嵌套承诺的目的是什么
- 嵌套承诺执行不同步
- 嵌套的 AJAX 调用列表和 $.when.apply - 延迟承诺无法正常工作
- AngularJs $q.all 不会用混合的嵌套承诺来解决
- 使用模拟工厂在茉莉花中测试嵌套承诺
- angular.foreach 解析嵌套承诺
- 如何避免用$q嵌套承诺
- 使用请求-承诺的嵌套异步请求