我一直试图让JavaScript承诺按预期工作。
我的代码:
var p = new Promise(function(resolve, reject) {
for (var i = 0; i < pics_needed.length; i++) {
download_pics(pics_needed[i])
}
for (var i = 0; i < partners_pics_needed.length; i++) {
partners_download_pics(partners_pics_needed[i])
}
resolve('Success!');
})
p.then(function() {
AsyncStorage.setItem("database",responseText)
AsyncStorage.removeItem("time")
alert ("Success! \nYour update has been installed.")
go()
});
for循环中调用的两个函数都从服务器下载图片。问题是,在下载所有图片之前,该功能的
p.then
部分正在运行。我该如何更改所有下载完成后p.then
部分?函数的作用:
function download_pics (id){
var path = RNFS.DocumentDirectoryPath + '/' + id + '.jpg';
fetch('address of server ='+id)
.then((response) => response.text())
.then((responseText) => {
var pic_object = JSON.parse(responseText)
RNFS.writeFile(path, pic_object.response, 'base64')
});
}
最佳答案
正如评论中所暗示的那样-如果您要落后于承诺,诺言并非一文不值。
function download_pics (id){
var path = RNFS.DocumentDirectoryPath + '/' + id + '.jpg';
return fetch('address of server ='+id) // <--- NOTE: return here
.then((response) => response.text())
.then((responseText) => {
var pic_object = JSON.parse(responseText)
return RNFS.writeFile(path, pic_object.response, 'base64') // <-- and here
});
}
接着
var pics_promises = pics_needed.map(function(pic) {
return download_pics(pic);
});
var partners_pics_promises = partners_pics_needed.map(function(pic) {
return partners_download_pics(pic);
});
return Promise.all(pics_promises.concat(partners_pics_promises));
编辑:将
RNFS.writeFile
添加到每个@adeneo的Promise链中(我不熟悉RNFS
)。