Skip to content

Instantly share code, notes, and snippets.

@yonatanmn
Last active April 6, 2016 12:07
Show Gist options
  • Save yonatanmn/5d1298f6c2b4aa9a948651be181f1123 to your computer and use it in GitHub Desktop.
Save yonatanmn/5d1298f6c2b4aa9a948651be181f1123 to your computer and use it in GitHub Desktop.
SEQUENCE function that will call PROMISE handlers when the promises RESOLVES in the sequence they were ordered ASAP.
var randP = (name)=>{
return new Promise((rs,rj) => {
let randTime = (Math.floor(Math.random() * 6) + 1) * 500; //500 to 3000
setTimeout(rs, randTime, name + ' ' + randTime);
});
};
var log = function(x){console.log(x)};
function thenLog(p){return p.then(log);}
var a = randP('1'); var b = randP('2'); var c = randP('3');
thenLog(a)
.then(()=>
thenLog(b)
.then(()=>
thenLog(c)
)
//OR same thing with reduce
[a,b,c].reduce((p,c)=>{
return p.then(()=>thenLog(c))
}, Promise.resolve())
/**
* function that will call promise handlers when the promises resolves in the sequence they were ordered ASAP.
*
* @param pArr [Promise]
* @param callsArr [Function]
*/
function sequence(pArr, callsArr){
let callsStack = callsArr.map(c=> {
return {
called: false,
val: undefined,
call(){
if(!this.called){
this.called = true;
c(this.val)
}
}
};
}
);
function callSeq() {
for (let i = 0; i < callsStack.length; i++) {
let c = callsStack[i];
if (c.val === undefined) {break;} //if need to support non-returning promises use 'fulfilled' flag
c.call();
}
}
pArr.map((p, i)=> {
p.then(val=> {
callsStack[i].val = val;
callSeq();
})
});
}
// usage example
var randP = (name)=>{
return new Promise((rs,rj) => {
let randTime = (Math.floor(Math.random() * 6) + 1) * 500; //500 to 3000
setTimeout(rs, randTime, name + ' ' + randTime);
});
};
var log = function(x){console.log(x)};
sequence([randP('a'),randP('b'),randP('c')], [log,log,log]);
// => will always log 'a' 'b' 'c' asap
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment