Quantcast
Channel: Ionic Forum - Latest topics
Viewing all articles
Browse latest Browse all 70439

How to implement a cancel function to several downloads being made using Promise.all()

$
0
0

@leonardofmed wrote:

I have a Promise.all() that returns when all my download promises are finished, the downloads are basically several images. I’m trying to add the possibility to cancel the remainig downloads in the list of urls that is passed to Promise.all(). I tried some ways to do this, but the remainig items are always downloaded anyway.

How my code is right now:

async downloadFunction(arrayToDownload: Object[]): Promise<void[]> {
	let loading = await this.loadingController.create({
		message: 'Touch backgroud to cancel',
		backdropDismiss: true
	});
	await loading.present();

	const fileTransfer: FileTransferObject = this.transfer.create();
	let canceled: boolean = false;

	loading.onDidDismiss().then(obj => {
		console.log(obj); // obj.role will be = 'backdrop' if clicked in background
		if (obj.role === 'backdrop') {
			console.log('canceled');
			//fileTransfer.abort(); -> Tried to abort filetransfer here first, but it seems that it need to be fired during download.
			canceled = true;
			return;
		}
	}); 

	return Promise.all(arrayToDownload.map(element => {
		if (canceled === true) {
			return;	// Added a return here, so it would skip the rest, but didn't work					
		}

		if (element != undefined) {
			// Get data from URL and do other preparations
			//...

			return fileTransfer.download(encodedURI, this.file.externalDataDirectory + 'randomFolder').then(entry => {
				return;
			
			}, error => {
				console.log("Error while downloading image: ", error);
				return;		
			}).catch(error => {
				console.log("Error while downloading image: ", error);
				return;
			}); 
		} else {
			throw new Error("image url not available");  				
		}

	})).then(() => {
		loading.dismiss();
		return [];
	});
}

Posts: 1

Participants: 1

Read full topic


Viewing all articles
Browse latest Browse all 70439

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>