Skip to content

Instantly share code, notes, and snippets.

@cuteribs-1
Last active September 27, 2019 18:42
Show Gist options
  • Save cuteribs-1/ba600486daea08bc4d6b9b1d0d6441e5 to your computer and use it in GitHub Desktop.
Save cuteribs-1/ba600486daea08bc4d6b9b1d0d6441e5 to your computer and use it in GitHub Desktop.
/*
* this is an example of how to limit the amount of promise tasks in parallel.
*/
let urls = getUrls(); // the array of image urls.
const maxTasks = 5; // the max amount of promise task in parallel.
let uploadAttemps = 0; // upload attemps
const uploadImage = () =>
new Promise((resolve, reject) => {
// gives up when upload attemps reach to 100.
if(uploadAttemps >= 100) {
reject();
return;
}
const url = urls.shift();
if(!url) {
resolve();
return;
}
uploadTries++;
const uploadUrl = 'https://example.com/upload-path';
$.ajax({
url: uploadUrl,
method: 'POST',
data: { url }
}).done(res => {
if (res.code === 0) {
console.log(`${url} is uploaded.`);
} else {
// puts current url back to the array.
urls.unshift(url);
}
// continues to upload the rest images.
uploadImage().then(res => resolve());
});
});
const promises = [...Array(3).keys()].map(x => uploadImage());
Promise.all(promises).then(res => console.log('work completed.'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment