我一直在尝试找出为该功能写一个诺言的正确方法。我有一个异步功能,该功能向服务器发出HTTP请求以检索响应“ documents_fileUploader”。我通过响应中每个项目的“ URL”进行映射,每个URL都将进入一个函数,该函数发出另一个HTTP请求,然后设置状态。我只想在完成“ documents_fileUploader()”函数中的所有操作后才触发“ upload()”函数。我试图在没有任何承诺的情况下执行此操作,并且由于请求仍处于待处理状态,因此直接进入了我的“ upload()”函数。有什么建议可以解决吗?
documents_fileUploader(formData).then(resp => {
resp.data.items.map(url => {
const key = url.split("/")[4];
this.setState({
urls: [...this.state.urls, url],
keys: [...this.state.keys, key]
});
this.getFileObject(key);
})
}).then(() => {
this.upload();
})
getFileObject = file => {
file_view(file).then(resp => {
this.setState({
mimeTypes: [...this.state.mimeTypes, resp.data.item.headers.contentType]
})
}).catch(err => {
console.log(err);
})
}
答案 0 :(得分:2)
Promise.all
方法来等待.map
调用返回的所有诺言。getFileObject
函数必须返回它创建的承诺。因此,结合这两个更改,您的代码段可能看起来像:
documents_fileUploader(formData).then(resp => {
return Promise.all(resp.data.items.map(url => { // Wrap in Promise.all and return it
const key = url.split("/")[4];
this.setState({
urls: [...this.state.urls, url],
keys: [...this.state.keys, key]
});
return this.getFileObject(key); // Make sure to return this promise as well.
}));
}).then(() => {
// Now this won't happen until every `getFileObject` promise has resolved...
this.upload();
})
getFileObject = file => {
return file_view(file).then(resp => { // And return the promise here.
this.setState({
mimeTypes: [...this.state.mimeTypes, resp.data.item.headers.contentType]
})
}).catch(err => {
console.log(err);
})
}