0
I am making a code that makes two requests, the value returned is the size of a file content-length
, but I need the function that contains these two requests to return the value after the requests are finished (Yes, they take a while). But I don’t know how to handle this demand for requisitions.
Being more detailed, when I call the function: addItem
the function saveFiles
will be called, within this function will be called two more functions (sometimes only one depending on the type of media) _getImage
and _getVideo
, these two functions will download the media and save on mobile and return the file size. Put inside saveFiles
functions are returning before they even finish, so I don’t have the size value when I need it.
I tried to use the async
and the await
, but I have not succeeded, yet my duties are not waiting. Is there any way to wait for a promise to finish and then execute the promised step?
import RNFetchBlob from 'rn-fetch-blob';
export default class Manager {
constructor(maxSize) {
this.maxSize = maxSize;
this.listOfFiles = [];
this.dirs = RNFetchBlob.fs.dirs;
}
addItem(item, media) {
size = this.saveFiles(item);
console.log(size);
this.listOfFiles.push({
inFeed: false,
media: media,
})
}
seeFiles() {
for(i = 0 ; i < this.listOfFiles.length; i++) {
console.log(this.listOfFiles[i])
}
}
saveFiles(item) {
var sizeImage = 0;
var sizeVideo = 0;
if(item.type == 'Animated') {
sizeVideo = this._getVideo(item.images.image460svwm.url);
sizeImage = this._getImage(item.images.image460.url);
} else {
sizeImage = this._getImage(item.images.image460.url);
}
return sizeImage + sizeVideo;
}
async _getImage(url) {
var filename = url.substring(url.lastIndexOf('/')+1);
return await RNFetchBlob.config({
// add this option that makes response data to be stored as a file,
// this is much more performant.
fileCache : true,
path : this.dirs.DocumentDir + '/media/' + filename
})
.fetch('GET', url, {
//some headers ..
})
.then((res) => {
console.log(res.respInfo.headers['content-length'])
return res.respInfo.headers['content-length']
})
}
async _getVideo(url) {
var filename = url.substring(url.lastIndexOf('/')+1);
return await RNFetchBlob.config({
// add this option that makes response data to be stored as a file,
// this is much more performant.
fileCache : true,
path : this.dirs.DocumentDir + '/media/' + filename
})
.fetch('GET', url, {
//some headers ..
})
.then((res) => {
console.log(res.respInfo.headers['content-length'])
return res.respInfo.headers['content-length']
})
}
}
It is important to point out that: If any of the past promises are rejected, the
Promise.all
rejects asynchronously with the value of the promise that was rejected– Cristiano Gilberto João