Last active
September 27, 2019 18:42
-
-
Save cuteribs-1/ba600486daea08bc4d6b9b1d0d6441e5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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