Created
February 15, 2017 07:57
-
-
Save sweet-zone/5a903f11e04174eca83c8c13c3e1d7c1 to your computer and use it in GitHub Desktop.
promise 顺序执行
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
// promise 和 reduce | |
(function() { | |
function sequenceTasks(tasks) { | |
function recordValue(results, value) { | |
results.push(value); | |
return results; | |
} | |
var pushValue = recordValue.bind(null, []); | |
return tasks.reduce(function(promise, task) { | |
return promise.then(task).then(pushValue) | |
}, Promise.resolve()) | |
} | |
function randomNum(min, max) { | |
return Math.floor(Math.random() * (max - min) + min); | |
} | |
function upload(file) { | |
return new Promise(function(resolve, reject) { | |
console.log('handle - ' + file) | |
setTimeout(function() { | |
if(randomNum(1000, 2000) % 2 === 0) { | |
resolve(file + ' - success') | |
} else { | |
reject(file + ' - fail'); | |
} | |
}, randomNum(1000, 2000)) | |
}) | |
} | |
function main() { | |
var tasks = []; | |
function task(f) { | |
return upload(f).catch(function(err) { | |
return err | |
}) | |
} | |
for(var i = 0; i < 5; i++) { | |
tasks.push( | |
task.bind(null, i) | |
) | |
} | |
return sequenceTasks(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