Skip to content

Instantly share code, notes, and snippets.

@luokebi
Last active August 29, 2015 14:00
Show Gist options
  • Save luokebi/24a880e6d492a348971a to your computer and use it in GitHub Desktop.
Save luokebi/24a880e6d492a348971a to your computer and use it in GitHub Desktop.
promise test
function log (str) {
document.body.innerHTML += str + '<br/>';
}
function Promise (func) {
var z = this;
this._thens = [];
function resolve () {
var args = Array.prototype.slice.call(arguments);
var fun = z._thens.shift();
if (fun) {
var p = fun.apply(null, args);
if (p instanceof Promise) {
p._thens = z._thens;
} else {
var promise = new Promise(function(resolve) {
setTimeout(function () {
resolve(p);
});
});
promise._thens = z._thens;
}
}
}
func.call(null, resolve);
}
Promise.prototype.then = function (fun) {
this._thens.push(fun);
return this;
};
Promise.resolve = function () {
var args = Array.prototype.slice.call(arguments);
var promise = new Promise(function(resolve){
resolve.apply(null, args);
});
return promise;
};
Promise.all = function (promises) {
var len = promises.length;
var defer = Promise.deferred();
var results = [];
for(var i = 0; i < len; i++) {
(function (i) {
var p = promises[i];
p.then(function (r) {
results[i] = r;
if (results.length === len) {
defer.resolve(results);
}
});
})(i);
}
return defer.promise;
};
Promise.any = function (promises) {
var len = promises.length;
var defer = Promise.deferred();
var results = [];
for(var i = 0; i < len; i++) {
(function (i) {
var p = promises[i];
p.then(function (r) {
results[i] = r;
if (results.length > 0) {
defer.resolve(r);
}
});
})(i);
}
return defer.promise;
};
Promise.queue = function (funcs) {
var temp_p = funcs[0]();
for (var i = 1, len = funcs.length;i < len; i++) {
(function (i) {
temp_p.then(funcs[i]);
})(i);
}
return temp_p;
};
Promise.deferred = function () {
var defer = {};
defer.promise = new Promise(function (resolve) {
defer.resolve = resolve;
});
return defer;
};
function a1 () {
var promise = new Promise (function (resolve) {
setTimeout(function () {
log('a1');
resolve('a1');
},2000);
});
return promise;
}
function a2 () {
var defer = Promise.deferred();
setTimeout(function () {
log('a2');
defer.resolve('a2');
}, 1000);
return defer.promise;
}
function b (txt) {
return txt + "b";
}
function c (txt) {
return new Promise (function (resolve) {
setTimeout(function () {
resolve(txt + 'c');
},1000);
})
}
function d (txt) {
log(txt + "d");
return txt + "d";
}
function e (txt) {
log(txt + 'e');
}
// test
var test;
//a().then(b).then(c).then(d).then(e);
Promise.queue([a1,a2,c]).then(function (arr) {
console.log(arr.length, arr);
test = arr;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment