Skip to content

Instantly share code, notes, and snippets.

@vaidd4
Created January 12, 2021 22:50
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 vaidd4/22131e7bd061b85ca1c919163a6a688e to your computer and use it in GitHub Desktop.
Save vaidd4/22131e7bd061b85ca1c919163a6a688e to your computer and use it in GitHub Desktop.
Callback-based function to promise-based function.
function cbtoasync(fncb, ...params) {
return new Promise((res, rej) => {
fncb(...params, (...data) => {res(...data)})
})
}
function tr_cbtoasync(fncb) {
return (...data) => cbtoasync(fncb, ...data)
}
/* Tests */
function testcb(data, cb) {
cb(data)
}
testcb("hello", d => console.log(d + " world"))
cbtoasync(testcb, "hi").then(d => d + " dude").then(console.log)
const test = tr_cbtoasync(testcb)
test("yo").then(d => d + " bud").then(console.log)
;(async () => {
const h = await test("hola")
console.log(h + " amigo")
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment