Skip to content

Instantly share code, notes, and snippets.

@andrelandgraf
Last active July 30, 2018 20:27
Show Gist options
  • Save andrelandgraf/dc0688cca8e9727693bb4d34a1669a87 to your computer and use it in GitHub Desktop.
Save andrelandgraf/dc0688cca8e9727693bb4d34a1669a87 to your computer and use it in GitHub Desktop.
working with function expressions and chaining of promises
/*
* working with resolve()
*/
const doSomethingChained = (name) => {
console.log('1');
return new Promise((resolve, reject) => setTimeout(() => {console.log(name); resolve();}, 1500, name));
};
doSomethingChained('Alice').then(() => {
console.log('2');
});
/* => Output:
* 1
* Alice
* 2
* Task 1: main code
* Task 2: the setTimeout call create a new task for the event loop
* We are chaining the two tasks, meaning that we await termination in taks 2 and than continue with resolve() in taks 1 again
*/
/*
* working reject() (the wrong way)
*/
const doSomethingBadChained = (name) => {
console.log('1');
return new Promise((resolve, reject) => setTimeout(() => {console.log(name); reject('Oops, Something Went Wrong!');}, 1500, name));
};
doSomethingBadChained('Alice').then(() => {
console.log('2');
});
/* => Output:
* 1
* Alice
* Error: UnhandledPromiseRejectionWarning: Error: Oops, Something Went Wrong!
* we crashed!
*/
/*
* working reject()
*/
const doSomethingBadChained2 = (name) => {
console.log('1');
return new Promise((resolve, reject) => setTimeout(() => {console.log(name); reject(Error('Oops, Something Went Wrong!'));}, 1500, name));
};
doSomethingBadChained2('Alice').catch((err) => {
console.log(err);
console.log('2');
});
/* => Output:
* 1
* Alice
* Error: Oops, Something Went Wrong!
at Timeout.setTimeout [as _onTimeout] (C:\Users\Andre.Landgraf\WebstormProjects\node-party\index.js:53:89)
at ontimeout (timers.js:486:15)
at tryOnTimeout (timers.js:317:5)
at Timer.listOnTimeout (timers.js:277:5)
* 2
* Answer: catching the error allows us to continue the process and handle it in an appropriate way (telling the user)
* Also, returning an actual Error Object allows us to receive the stack trace of the error which will help tracking down the issue.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment