2016-05-11 54 views
0

我不得不在承诺之内嵌入一个承诺,这是好的,还是认为不好的做法?嵌套承诺的并行效果?

  1. 我已经拥有一个方法,fetchArticlesfetchImages,并main类。
    • main是调用fetchArticles + fetchImages
    • fetchArticles运行从它返回一个承诺其他文件的功能之一,但我也对fetchArticles类方法本身返回一个承诺,所以当它获取的文章,它会继续并获取图像。
    • fetchImages方法不承诺,但从另一个文件调用承诺的功能。

我不能确定这是否是实现parralel效果最好的方法是什么?

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") 
    }) 
    } 
} 

我应该使用类似async parallel的东西吗?注意我暂时在fetchImages方法中添加了一个callback,直到我找到链接承诺的好解决方案。

+1

嵌套的承诺是好:) – winhowes

回答

1

的几个注意事项:

  1. 要创建在fetchArticles功能的不必要的承诺。您可以直接返回promisified fetchArticles的结果。

  2. 使用Promise.all可以让你同时触发两个项目。如果你的两种方法不依赖于对方,那么这是一个好方法。我用该代码更新了main函数。

  3. 同样,您可以直接在您的fetchImages函数中返回承诺。因为这也是promisified,你不再需要回调。我已将其删除。

生成的代码

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") 
    }) 
    } 
} 
+0

我已经决定接受你的,因为它是很多更详细的! – James111

+0

当然可以。查看我的解释性编辑,了解其他可能有用的信息。 – Paarth