Skip to content

Instantly share code, notes, and snippets.

@nexpr
Created February 5, 2017 08:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nexpr/0e515ee5f82b2f4c2926e5a2e6e23fa4 to your computer and use it in GitHub Desktop.
Save nexpr/0e515ee5f82b2f4c2926e5a2e6e23fa4 to your computer and use it in GitHub Desktop.
asyncnize
Function.prototype.async = function(pos){
return (...args) =>
new Promise((resolve, reject) => {
var iidx = Object.is(-0, pos) ? args.length : pos
var cb = (...cbarr) => resolve(cbarr)
args.splice(iidx, 0, cb)
this(...args)
})
}
Function.prototype.lasync = function(...args){
return this.async(0)(...args)
}
Function.prototype.rasync = function(...args){
return this.async(-0)(...args)
}
!async function(){
console.log(new Date())
await setTimeout.async(0)(2000)
console.log(new Date())
}()
function wait(msec, cb){
setTimeout(cb, msec)
}
wait(2000, () => console.log(1))
!async function(){
console.log(new Date())
await wait.async(-0)(2000)
console.log(new Date())
}()
!async function(){
console.log(new Date())
await setTimeout.lasync(2000)
console.log(new Date())
}()
!async function(){
console.log(new Date())
await wait.rasync(2000)
console.log(new Date())
}()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment