Skip to content

Instantly share code, notes, and snippets.

@m28dev
Created May 23, 2021 11:56
Show Gist options
  • Save m28dev/46e05c6cc0cfe75365ed98aa2013b8a5 to your computer and use it in GitHub Desktop.
Save m28dev/46e05c6cc0cfe75365ed98aa2013b8a5 to your computer and use it in GitHub Desktop.
Convert callback function to promise
// 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