Skip to content

Instantly share code, notes, and snippets.

@DadgadCafe
Last active March 21, 2017 06:31
Show Gist options
  • Save DadgadCafe/1249459474da82f9a6739fb7e104134c to your computer and use it in GitHub Desktop.
Save DadgadCafe/1249459474da82f9a6739fb7e104134c to your computer and use it in GitHub Desktop.
The simplest promise implementation.
'use strict'
function promisify (fakeAjax){
let content = null
let func = null
return function (url) {
fakeAjax(url, (err, data) => {
if (err) {
throw Error('unhandled error')
}
if (func) {
return func(data)
}
return content = data
})
return function (then) {
if (content) {
return then(content)
}
return func = then
}
}
}
function fakeAjax (url, cb) {
setTimeout(
() => {cb(null, 'all done')},
2000
)
}
function log (content) {
console.log(content)
}
// called after 2s
promisify(fakeAjax)('fake url')(log)
const p = promisify(fakeAjax)('fake url')
setTimeout(
() => {
// called after 2s
log('calling p now')
// called immediately after log 'calling p now'
p(log)
},
2000
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment