Created
April 15, 2016 11:58
-
-
Save Orbifold/b03c70b3ebfcf5b4b13a3ccae50a581e to your computer and use it in GitHub Desktop.
Chaining promising so they execute sequentially.
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Title</title> | |
</head> | |
<body> | |
<script type="text/javascript"> | |
var getters = []; | |
function getPromise(k) { | |
return new Promise(function(resolve, reject) { | |
setTimeout(function() { | |
console.log("3." + k); | |
resolve(k); | |
}, parseInt(Math.random() * 5000)) | |
}); | |
} | |
function first() { | |
//console.log("First"); | |
return 1; | |
} | |
function second() { | |
return new Promise(function(resolve) { | |
setTimeout(function() { | |
//console.log("Second"); | |
resolve(2); | |
}, parseInt(Math.random() * 5000)) | |
}); | |
} | |
function third() { | |
//console.log("Third"); | |
for(var i = 0; i < 5; i++) { | |
getters.push(getPromise(i)); | |
} | |
return Promise.all(getters).then(function(ks) { | |
return 3; | |
}); | |
} | |
function fourth() { | |
//console.log("Fourth"); | |
return 4; | |
} | |
function fifth() { | |
return new Promise(function(resolve) { | |
setTimeout(function() { | |
//console.log("Second"); | |
resolve(5); | |
}, 5000) | |
}); | |
} | |
var seq = [first, second, third, fourth, fifth]; | |
var currentIndex = -1; | |
function next() { | |
currentIndex++; | |
if(currentIndex < seq.length) { | |
var p = seq[currentIndex](); | |
return Promise.resolve(p).then(function(value) { | |
console.log(value); | |
return next(); | |
}); | |
} | |
return "Pipeline done."; | |
} | |
next().then(function(v) { | |
console.log(v); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment