Created
September 11, 2018 02:32
-
-
Save Yuyz0112/1d3185f17fe647caf43153f03ddb8264 to your computer and use it in GitHub Desktop.
show the differences between callback, promise and async-await
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
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