After extensive searching online, I am still grappling with this particular issue.
Currently, I'm developing an Angular service for an Ionic application. This service's primary function is to download an image. In traditional JavaScript, I would typically tackle this problem using recursive calls to prevent repetition in my code.
I attempted to implement the solution using promises to familiarize myself with the concept, but I've encountered some challenges along the way.
Take a look at the following code snippet:
public getBgForName = (name: string) => {
name = name.toLowerCase();
var instance = this;
var dir = this.file.dataDirectory;
return new Promise(function (fulfill, reject) {
instance.file.checkDir(dir, name).then(() => {
// directory exists. Is there a bg file?
dir = dir + '/' + name + '/';
instance.file.checkFile(dir, 'bg.jpg').then(() => {
console.log('read file');
fulfill(dir + '/' + 'bg.jpg')
}, (err) => {
// dl file and re-call
console.log('needs to download file!')
instance.transfer.create().download(encodeURI('https://host.tld/'+name+'/bg.jpg'), dir + 'bg.jpg', true, {})
.then((data) => {
return instance.getBgForName(name).then((url) => {return url});
}, (err) => {
console.log(err)
})
})
}, (err) => {
// create dir and re-call
instance.file.createDir(dir, name, true).then(() => {
instance.getBgForName(name).then((url) => {fulfill(url)});
})
})
});
}
When invoked, the promise never seems to fully resolve. Upon reading this article, it appears that the issue lies in the correct passing of resolved promises within the chain - causing the resolution only up to a certain level, but not all the way to the top. Evidently, when the conditions mentioned below are met, the promise resolves correctly:
The directory is already created
The file is already downloaded
Hence, I suspect that the return statements somehow disrupt the connection here, preventing the promise from resolving after the initial recursive call.
What is the appropriate method for recursively calling a promise while ensuring that the original caller receives the result once it becomes available?
Edit: Per David B.'s suggestion, I will outline the desired outcome. The objective of this code segment is to have a function that processes a list of items. Each item corresponds to a background image stored on a server, which is then cached locally. The rationale behind utilizing recursive calls is to consistently return a URL to the local filesystem housing the image, regardless of its current status (downloaded or pending). The workflow is as follows:
- Create a directory for the current item
- Download the file into this directory
- Return a local URL pointing to the downloaded file
Subsequent calls should merely retrieve the image directly from disk (after confirming its existence), without any additional downloads.