Last active
September 14, 2017 07:24
-
-
Save alexandrebodin/83611afb94348a2b3adfd3cc9360932b to your computer and use it in GitHub Desktop.
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
const proto = { | |
timeout: null, | |
promise: null, | |
racer: null, | |
then(fn) { | |
this.promise = this.promise.then(result => { | |
return Promise.race([this.racer, fn(result)]); | |
}); | |
return this; | |
}, | |
run(fn) { | |
this.promise = this.promise.then(fn, fn); | |
return this; | |
}, | |
catch(fn) { | |
this.promise = this.promise.catch(fn); | |
return this; | |
}, | |
end() { | |
this.promise.then(() => { | |
clearTimeout(this.timeout); | |
}) | |
return this.promise; | |
} | |
}; | |
const chainer = time => { | |
let timeout; | |
return fn => { | |
const racer = new Promise((res, rej) => { | |
timeout = setTimeout(() => { | |
console.log('finished'); | |
rej(new Error('TIME_OUT')); | |
}, time); | |
}); | |
return Object.assign(Object.create(proto), { | |
timeout, | |
racer, | |
promise: Promise.race([racer, fn()]), | |
}); | |
}; | |
}; | |
// ********* | |
// EXAMPLE | |
// ********* | |
chainer(1000)(() => { | |
return new Promise(res => { | |
setTimeout(() => res('hello'), 100); | |
}); | |
}) | |
.then(s => { | |
console.log(s); | |
return new Promise(res => { | |
setTimeout(() => { | |
res('coucou'); | |
}, 2000); | |
}); | |
}) | |
.then(s => { | |
console.log(s); | |
return new Promise(res => { | |
setTimeout(() => { | |
res('coucou2'); | |
console.log('coucou2'); | |
}, 2000); | |
}); | |
}) | |
.run(() => { | |
// runs anyway | |
console.log('runs anyway') | |
return 'runs' | |
}) | |
.catch(err => { | |
console.log('coucou error: ', err); | |
}) | |
.end() | |
.then(res => { | |
console.log('after chainer ends you get the real promise behind') | |
console.log(res); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment