Skip to content

Instantly share code, notes, and snippets.

@sweet-zone
Created February 15, 2017 07:56
Show Gist options
  • Save sweet-zone/bfc5628e5317eeeb34d98ef59b810cf4 to your computer and use it in GitHub Desktop.
Save sweet-zone/bfc5628e5317eeeb34d98ef59b810cf4 to your computer and use it in GitHub Desktop.
Promise.all 同时执行多个任务
// http://stackoverflow.com/questions/30362733/handling-errors-in-promise-all
// https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
(function() {
function randomNum(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
function upload(file) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
if(randomNum(1000, 2000) % 2 === 0) {
resolve(file + ' - success')
} else {
reject(file + ' - fail');
}
}, randomNum(1000, 2000))
})
}
function main() {
var tasks = [];
for(var i = 0; i < 5; i++) {
tasks.push(
upload(i).catch(function(err) {
return err
})
)
}
return Promise.all(tasks)
}
main().then(function(value) {
console.log(value)
})
.catch(function(err) {
console.log(err)
})
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment