2017-06-14 32 views
0

我正在使用React-Redux操作一次獲取一些Promise響應。事實是,我需要在一個聯合響應中鏈接這些響應。 我有一個解析JSONs響應的函數。Javascript:無法一起獲取Promises.all響應

例如:

Promise.all([ 
     fetch('some_backend_resource'), 
     fetch('another_backend_resource')]) 
.then(([response1, response2]) => { 
    parseJSON(response1).then(resp1 => { 
    // here I dispatch to another function the value of resp1 
    }); 
    parseJSON(response2).then(resp2 => { 
    // here I dispatch to another function the value of resp2   
    }); 
}) 

然後我通過resp1和resp2值各自的減速,背視圖組件我試圖把它們放在一起,但有時這是行不通的,因爲resp1道具獲得在resp2道具之前的ComponentDidmount。 如何將它們組合成單個響應,然後將它傳遞給視圖組件?

+0

爲什麼'parseJSON()'異步?這看起來不應該是這樣,這會讓你的問題更加困難。 – jfriend00

+0

@ jfriend00可能是因爲'fetch'響應對象有一個異步'json'方法來解析響應... – Brandon

回答

1

你的問題並不完全清楚。如果你想派遣前解析兩種反應,那麼最簡單的方式是鏈解析到獲取和結果使用Promise.all

Promise.all([ 
    fetch('some_backend_resource').then(r => parseJSON(r)), 
    fetch('another_backend_resource').then(r => parseJSON(r))]) 
.then(([resp1, resp2]) => { 
    // dispatch resp1 & resp2 
}); 
+0

感謝您的回覆我正在使用它。 – assembler