2015-11-05 72 views
0

我正在做一系列使用HTML5 API的文件上傳,我希望連續運行一個Promises集合,並且只在所有文件上傳時才做最後的PUT。你如何鏈接HTML5 fetch()?

目前,這是我有:

obj.attachments.forEach((file) => {                
    const request = fetch(`${window.location.origin}/api/cases/${obj.id}/attachment`, {    
    ...baseSettings,                    
    body: file,                      
    headers: {},                     
    }).then((req) => req.json())                  
    .then((json) => { console.log('upload ', json); });            
});                         


const request = fetch(`${window.location.origin}/api/cases`, putJSON(_.omit(obj, 'attachments'))); 
request.then((req) => req.json())                 
     .then((json) => dispatch(receiveCase(json)));            

理想情況下,obj.attachments會轉化爲承諾的集合,最終獲取可追加,他們將陸續全部運行。

+0

使用時,所有的承諾都做到A Q包才讓看跌電話! –

+2

只從這個問題稍作修改:http://stackoverflow.com/questions/31710768/how-can-i-fetch-an-array-of-urls-with-promise-all –

回答

1

感謝約拿,這裏是我的解決方案:

return Promise.all(kase.attachments.map((file) => {             
    return fetch(`${window.location.origin}/api/cases/${kase.id}/attachment`, {       
    ...baseSettings,                     
    body: file,                      
    headers: {},                      
    }).then((req) => req.json()).then((json) => {              
    console.log(json, file);                   
    });                         
})).then(files => {                     
    const request = fetch(`${window.location.origin}/api/cases`, putJSON(_.omit(kase, 'attachments'))); 
    return request                      
    .then((req) => req.json())                   
    .then((json) => dispatch(receiveCase(json)));              
});