你如何链接HTML5 fetch()?

时间:2015-11-05 09:42:19

标签: javascript html5 promise ecmascript-6 fetch-api

我正在使用HTML5 API进行一系列文件上传,我希望连续运行一系列Promise,并且只在上传所有文件时执行最终PUT。

目前,这就是我所拥有的:

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将被转换为Promises的集合,并且可以附加最终的提取,并且它们将连续运行。

1 个答案:

答案 0 :(得分:1)

感谢Jonah,这是我的解决方案:

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