我正试图让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')
});
}
答案 0 :(得分:2)
正如评论中所暗示的那样 - 如果你想要落后于他们,承诺并非毫无价值。
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的承诺链中(我不熟悉RNFS
)。