【发布时间】:2015-10-03 12:15:28
【问题描述】:
我有一个类似数组的结构,它公开了异步方法。异步方法调用返回数组结构,进而公开更多异步方法。我正在创建另一个 JSON 对象来存储从该结构获得的值,因此我需要小心跟踪回调中的引用。
我编写了一个蛮力解决方案,但我想学习一个更惯用或更干净的解决方案。
- 对于 n 层嵌套,该模式应该是可重复的。
- 我需要使用 promise.all 或一些类似的技术来确定何时解析封闭例程。
- 并非每个元素都必然涉及进行异步调用。所以在嵌套的 promise.all 中,我不能简单地根据索引对我的 JSON 数组元素进行赋值。不过,我确实需要在嵌套的 forEach 中使用 promise.all 之类的东西,以确保在解析封闭例程之前已完成所有属性分配。
- 我正在使用 bluebird promise lib,但这不是必需的
这里是部分代码 -
var jsonItems = [];
items.forEach(function(item){
var jsonItem = {};
jsonItem.name = item.name;
item.getThings().then(function(things){
// or Promise.all(allItemGetThingCalls, function(things){
things.forEach(function(thing, index){
jsonItems[index].thingName = thing.name;
if(thing.type === 'file'){
thing.getFile().then(function(file){ //or promise.all?
jsonItems[index].filesize = file.getSize();
【问题讨论】:
-
这是我想要改进的工作源的链接。 github.com/pebanfield/change-view-service/blob/master/src/…
-
我在示例中看到您正在使用 bluebird,在这种情况下,bluebird 实际上使用
Promise.map(并发)和Promise.each(顺序)让您的生活更加轻松 ,另请注意Promise.defer已弃用 - 我的答案中的代码显示了如何通过 returning 承诺来避免它。 Promise 都是关于返回值的。
标签: javascript node.js asynchronous promise