Skip to content

Instantly share code, notes, and snippets.

@jagomf
Last active June 5, 2019 11:22
Show Gist options
  • Save jagomf/c8989388b14294db7bbcecdcf28f079b to your computer and use it in GitHub Desktop.
Save jagomf/c8989388b14294db7bbcecdcf28f079b to your computer and use it in GitHub Desktop.
Promises to async/await
// Function with a promise
const doAsyncStuff = () => {
return new Promise((resolve, reject) => {
if (stuff) {
resolve('cool');
}
reject('bad');
});
};
// Promise function resolution, old style
main() {
doAsyncStuff().then(res => {
// res === 'cool'
}).catch(err => {
// err === 'bad'
});
}
// Promise function resolution, async/await style
async main() {
try {
const isCool = await asyncStuff();
// isCool === 'cool'
} catch (err) {
// err === 'bad'
}
}
// Inline promise resolution, old style
main() {
new Promise((resolve, reject) => {
if (stuff) {
resolve('cool');
}
reject('bad');
}).then(res => {
// res === 'cool'
}).catch(err => {
// err === 'bad'
});
}
// Inline promise resolution, async/await style
async main() {
const asyncStuff = () => new Promise((resolve, reject) => {
if (stuff) {
resolve('cool');
}
reject('bad');
});
try {
const isCool = await asyncStuff();
// isCool === 'cool'
} catch (err) {
// err === 'bad'
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment