Last active
March 21, 2017 06:31
-
-
Save DadgadCafe/1249459474da82f9a6739fb7e104134c to your computer and use it in GitHub Desktop.
The simplest promise implementation.
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
'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