Skip to content

Instantly share code, notes, and snippets.

@Yuyz0112
Created September 11, 2018 02:32
Show Gist options
  • Save Yuyz0112/1d3185f17fe647caf43153f03ddb8264 to your computer and use it in GitHub Desktop.
Save Yuyz0112/1d3185f17fe647caf43153f03ddb8264 to your computer and use it in GitHub Desktop.
show the differences between callback, promise and async-await
function longTask(int, callback) {
if (int < 0) {
callback(new Error('less than 0'));
} else {
callback(null, 'done');
}
}
// callback
longTask(1, (err, result) => {});
// promise
const pLongTask = (int) => new Promise((resolve, reject) => {
longTask(int, (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
})
});
pLongTask(1)
.then((result) => {})
.catch((err) => {});
// async-await
(async function() {
try {
const result = await pLongTask(1);
} catch (error) {
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment