Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // A promise implementation that enables sequencing and flattening of an arbitrary
- // number of asyncronous functions, and allows a value to be passed through.
- function first() {
- return promise(function(resolve, val) {
- setTimeout(function() {
- console.log("first", val);
- resolve(2);
- }, 50);
- });
- }
- first().then(function(resolve, val) {
- setTimeout(function() {
- console.log("second", val);
- resolve(val+1);
- }, 110);
- }).then(function(resolve, val) {
- setTimeout(function() {
- console.log("third", val);
- resolve((val+1)*10);
- }, 60);
- }).then(function(resolve, val) {
- setTimeout(function() {
- console.log("fourth", val);
- resolve();
- }, 40);
- }).end();
- console.log("zeroth");
- // The code will output:
- // zeroth
- // first initVal
- // second 2
- // third 3
- // fourth 40
- function promise(f) {
- function callFns(arr, val) { // Call functions in order and pass the val argument
- if (arr.length == 1) {
- return arr[0](function() {}, val);
- } else {
- arr[0](function(n) { // n is the resolve argument
- callFns(arr.slice(1), n);
- }, val);
- }
- }
- var fns = [f]; // List of functions to call
- var res = {
- then: function(next) {
- fns.push(next);
- return res; // Recursively enable an arbitrary number of then-calls
- },
- end: function() {
- callFns(fns, "initVal"); // Pass all functions to be called together
- // with 'val' for the first of them.
- }
- };
- return res;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement