Created
May 23, 2021 11:56
-
-
Save m28dev/46e05c6cc0cfe75365ed98aa2013b8a5 to your computer and use it in GitHub Desktop.
Convert callback function to promise
This file contains 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
// Callback (original) | |
someAsyncFunction('params', (err, data) => { | |
if (err) throw err; | |
console.log('Callback:', data); | |
}); | |
// to Promise | |
new Promise((resolve, reject) => { | |
someAsyncFunction('params', (err, data) => { | |
if (err) return reject(err); | |
resolve(data); | |
}); | |
}).then(data => { | |
console.log('Promise:', data); | |
}).catch(err => { | |
throw err; | |
}); | |
function someAsyncFunction(params, callback) { | |
setTimeout(() => { | |
callback(null, params); | |
}, 1 * 1000); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment