Skip to content

Instantly share code, notes, and snippets.

@patarkf
Created December 9, 2017 12:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patarkf/b0fadc72a3e859642dba54a0a867eaa2 to your computer and use it in GitHub Desktop.
Save patarkf/b0fadc72a3e859642dba54a0a867eaa2 to your computer and use it in GitHub Desktop.
/**
* Always waits one second, then "toss a coin", having
* a 50/50 chance to get either true or false. Throws
* an error if false.
*/
async function waitAndMaybeReject() {
await new Promise(r => setTimeout(r, 1000));
const isHeads = Boolean(Math.round(Math.random()));
if (isHeads) return 'yay';
throw Error('ihhh');
}
/**
* 1) Not returning neither awaiting.
*
* Async return without awaiting or returning the promise and its
* fulfilled or rejected value.
*
* This way the promise will always fulfill undefined, without waiting.
* It's like we don't react with the promise in any way.
*/
async function foo() {
try {
waitAndMaybeReject();
} catch (e) {
return 'caught';
}
}
/**
* 2) Just firing the promise (void kind)
*
* Ok, in this one, we are awaiting the fulfilled value,
* then if it rejects, our catch block will handle it;
* if it fulfills, still, we are not doing anything
* with the value.
*
* So it's not wrong in cases in which
* you just want to fire up a promise, but
* not do anything with its value.
*/
async function fooJustAwaitingPromise() {
try {
await waitAndMaybeReject();
} catch (e) {
return 'caught';
}
}
/**
* 3) Deferring promise
*
* In this case we are invoking the promise, however, we
* are deferring its fulfilled value to its invoker.
*
* It's important to say that the try/catch block is never
* executed here.
*/
async function fooReturningPromise() {
try {
return waitAndMaybeReject();
} catch (e) {
return 'caught';
}
}
/**
* 4) Returning awaited promise (fulfilled value)
*
* In this case we are returning the fulfilled value instead of the
* promise itself. If it resolves, we are returning the 'yay if it
* rejects we will return 'caught'.
*/
async function fooReturningAwaitedPromise() {
try {
return await waitAndMaybeReject();
} catch (e) {
return 'caught';
}
}
/**
* Same as the previous example, but this way assigning the resolved
* value to a variable, then returning it, just for illustration
* purposes.
*/
async function fooReturningAwaitedPromiseTwo() {
try {
const fulfilledValue = await waitAndMaybeReject();
return fulfilledValue;
} catch (e) {
return 'caught';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment