Skip to content

Instantly share code, notes, and snippets.

@jgfrancisco
Created March 13, 2020 13:35
Show Gist options
  • Save jgfrancisco/25d8ad24735333ad3d412f865c53e2a6 to your computer and use it in GitHub Desktop.
Save jgfrancisco/25d8ad24735333ad3d412f865c53e2a6 to your computer and use it in GitHub Desktop.
Promise short circuit behavior
const fn1 = (a, b, x) => new Promise((resolve, reject) => {
if (x) resolve('resolve x');
console.log('after x');
if (a) reject('reject a');
console.log('after a');
if (b) reject('reject b');
console.log('after b');
resolve('resolve c');
});
const fn2 = (a, b, x) => new Promise((resolve, reject) => {
if (x) return resolve('resolve x');
console.log('after x');
if (a) return reject('reject a');
console.log('after a');
if (b) return reject('reject b');
console.log('after b');
resolve('resolve c');
});
console.log('<< fn1 >>');
fn1(1, 1, 1)
.then(ret => console.log(ret))
.catch(err => console.log(err));
console.log('<< fn2 >>');
fn2(1, 1, 1)
.then(ret => console.log(ret))
.catch(err => console.log(err));
console.log('hello world');
@jgfrancisco
Copy link
Author

<< fn1 >>
after x
after a
after b
<< fn2 >>
hello world
resolve x
resolve x

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment