0

我正在使用 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将转换为 Promise 的集合,并且可以附加最终的 fetch 并且它们都将连续运行。

4

1 回答 1

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)));                                                     
});                                                                                                   
于 2015-11-05T10:42:03.993 回答