2016-05-11 73 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