SlideShare a Scribd company logo
By Mateusz Bryła
Promise((resolve, reject) => {
Math.random() > 0.5 ? resolve(love()) : reject(hate());
}).then(love => marry()).catch(hate => moveToAlaska());
Let’s talk about JavaScript...
https://www.destroyallsoftware.com/talks/wat ;)
What are we even talking about?
Promise Objects
Introduced: ECMAScript 2015 (previously ES6) - June 2015
Spec: https://www.ecma-international.org/ecma-262/6.0/#sec-promise-objects
Support: https://caniuse.com/#feat=promises
Polyfills:
- https://github.com/stefanpenner/es6-promise
- http://bluebirdjs.com/docs/install.html
Async / Await
Introduced: ECMAScript 2017 - June 2017
Spec: https://www.ecma-international.org/ecma-262/8.0/#sec-async-function-definitions
What are we even talking about?
Promise Objects
Introduced: ECMAScript 2015 (previously ES6) - June 2015
Spec: https://www.ecma-international.org/ecma-262/6.0/#sec-promise-objects
Support: https://caniuse.com/#feat=promises
What are we even talking about?
Promise Objects
Introduced: ECMAScript 2015 (previously ES6) - June 2015
Spec: https://www.ecma-international.org/ecma-262/6.0/#sec-promise-objects
Support: https://caniuse.com/#feat=promises
What are we even talking about?
Promise Objects
Introduced: ECMAScript 2015 (previously ES6) - June 2015
Spec: https://www.ecma-international.org/ecma-262/6.0/#sec-promise-objects
Support: https://caniuse.com/#feat=promises
What are we even talking about?
Promise Objects
Introduced: ECMAScript 2015 (previously ES6) - June 2015
Spec: https://www.ecma-international.org/ecma-262/6.0/#sec-promise-objects
Support: https://caniuse.com/#feat=promises
Polyfills:
- https://github.com/stefanpenner/es6-promise
- http://bluebirdjs.com/docs/install.html
What are we even talking about?
Promise Objects
Introduced: ECMAScript 2015 (previously ES6) - June 2015
Spec: https://www.ecma-international.org/ecma-262/6.0/#sec-promise-objects
Support: https://caniuse.com/#feat=promises
Polyfills:
- https://github.com/stefanpenner/es6-promise
- http://bluebirdjs.com/docs/install.html
Async / Await
Introduced: ECMAScript 2017 - June 2017
Spec: https://www.ecma-international.org/ecma-262/8.0/#sec-async-function-definitions
Support: https://caniuse.com/#feat=async-functions
What are we even talking about?
Promise Objects
Introduced: ECMAScript 2015 (previously ES6) - June 2015
Spec: https://www.ecma-international.org/ecma-262/6.0/#sec-promise-objects
Support: https://caniuse.com/#feat=promises
Polyfills:
- https://github.com/stefanpenner/es6-promise
- http://bluebirdjs.com/docs/install.html
Async / Await
Introduced: ECMAScript 2017 - June 2017
Spec: https://www.ecma-international.org/ecma-262/8.0/#sec-async-function-definitions
Support: https://caniuse.com/#feat=async-functions
Promise
“An object that is used as a placeholder for the eventual results of a deferred (and
possibly asynchronous) computation”
Promise p state is:
- fulfilled if p.then(f,r) enqueues a job to call f
- rejected if p.then(f,r) enqueues a job to call r
- pending if not fulfilled not rejected
- settled if not pending
- resolved if settled or locked in to match state of a different promise
function executeDelayed(operation, callback) {
setTimeout(() => {
try {
const result = operation();
callback(null, result);
} catch (error) {
callback(error);
}
}, 1000);
}
function executeDelayed(operation, callback) {
setTimeout(() => {
try {
const result = operation();
callback(null, result);
} catch (error) {
callback(error);
}
}, 1000);
}
executeDelayed(() => {
return 42;
}, (error, result) => {
if (error) {
console.log('delayed error', error);
} else {
console.error('delayed result', result);
}
});
const promise = new Promise((resolve, reject) => {
// perform action, call resolve / reject upon completion / error
});
promise.then((result) => {
// listen for completion
});
promise.catch((error) => {
// listen for error
});
promise.finally(() => {
// cleanup
});
function executeDelayed(operation, callback) {
setTimeout(() => {
try {
const result = operation();
callback(null, result);
} catch (error) {
callback(error);
}
}, 1000);
}
function executeDelayed(operation) {
return new Promise((resolve, reject) => {
setTimeout(() => {
try {
const result = operation();
resolve(result);
} catch (error) {
reject(error);
}
}, 1000);
});
}
function executeDelayed(operation, callback) {
setTimeout(() => {
try {
const result = operation();
callback(null, result);
} catch (error) {
callback(error);
}
}, 1000);
}
executeDelayed(() => {
return 42;
}, (error, result) => {
if (error) {
console.log('delayed error', error);
} else {
console.error('delayed result', result);
}
});
function executeDelayed(operation) {
return new Promise((resolve, reject) => {
setTimeout(() => {
try {
const result = operation();
resolve(result);
} catch (error) {
reject(error);
}
}, 1000);
});
}
executeDelayed(() => {
return 42;
}).then((result) => {
console.log('delayed result, result);
}).catch((error) => {
console.error('delayed error', error);
});
function log() { console.log(...arguments); }
p = new Promise((resolve, reject) => {
resolve(10);
}).then(x => log(x));
p = new Promise((resolve, reject) => {
resolve(10);
}).then(x => log(x));
// 10
p = new Promise((resolve, reject) => {
reject(10);
}).catch(x => log(x));
p = new Promise((resolve, reject) => {
reject(10);
}).catch(x => log(x));
// 10
p = new Promise((resolve, reject) => {
resolve(10);
resolve(20);
}).then(x => log(x));
p = new Promise((resolve, reject) => {
resolve(10);
resolve(20);
}).then(x => log(x));
// 10
p = new Promise((resolve, reject) => {
resolve(10);
reject(20);
}).then(x => log('F', x)).catch(x => log('R', x));
p = new Promise((resolve, reject) => {
resolve(10);
reject(20);
}).then(x => log('F', x)).catch(x => log('R', x));
// 10
p = new Promise((resolve, reject) => {
reject(20);
resolve(10);
}).then(x => log('F', x)).catch(x => log('R', x));
p = new Promise((resolve, reject) => {
reject(20);
resolve(10);
}).then(x => log('F', x)).catch(x => log('R', x));
// 20
const promise = new Promise((resolve, reject) => {
// perform action, call resolve / reject upon completion / error
});
promise.then((result) => {
// listen for completion
});
promise.catch((error) => {
// listen for error
});
promise.finally(() => {
// cleanup
});
Promise.resolve(10);
new Promise((resolve) => { resolve(10); });
Promise.reject(10);
new Promise((resolve, reject) => { reject(10); });
// fulfills if all fulfilled, rejected otherwise
Promise.all([Promise.resolve(10), Promise.reject(10)]);
// resolves as first resolves
Promise.race([Promise.resolve(10), Promise.reject(10)]);
Promise.resolve(10)
.then(x => log(x))
.then(x => log(x))
.then(x => log(x));
Promise.resolve(10)
.then(x => log(x))
.then(x => log(x))
.then(x => log(x));
// 10 undefined undefined
p = Promise.resolve(10);
p.then(x => log(x));
p.then(x => log(x));
p.then(x => log(x));
p = Promise.resolve(10);
p.then(x => log(x));
p.then(x => log(x));
p.then(x => log(x));
// 10 10 10
Promise.resolve(10)
.then(x => { log(x); return 20; })
.then(x => { log(x); return 30; })
.then(x => { log(x); });
Promise.resolve(10)
.then(x => { log(x); return 20; })
.then(x => { log(x); return 30; })
.then(x => { log(x); });
// 10 20 30
Promise.resolve(10)
.then(x => { log(x); return 20; })
.catch(x => { log(x); return 30; })
.then(x => { log(x); return 40; })
.then(x => { log(x); return 50; });
Promise.resolve(10)
.then(x => { log(x); return 20; })
.catch(x => { log(x); return 30; })
.then(x => { log(x); return 40; })
.then(x => { log(x); return 50; });
// 10 20 40
Promise.reject(10)
.catch(x => log(x))
.catch(x => log(x))
.catch(x => log(x));
Promise.reject(10)
.catch(x => log(x))
.catch(x => log(x))
.catch(x => log(x));
// 10
Promise.reject(10)
.catch(x => { log(x); return 20; })
.then(x => { log(x); return 30; })
.catch(x => { log(x); return 40; })
.then(x => { log(x); return 50; });
Promise.reject(10)
.catch(x => { log(x); return 20; })
.then(x => { log(x); return 30; })
.catch(x => { log(x); return 40; })
.then(x => { log(x); return 50; });
// 10 20 30
Promise.resolve(10)
.then(x => { log(x); return 20; })
.then(x => { log(x); throw new Error(30); })
.then(x => { log(x); return 40; })
.catch(x => { log(x); return 50; });
Promise.resolve(10)
.then(x => { log(x); return 20; })
.then(x => { log(x); throw new Error(30); })
.then(x => { log(x); return 40; })
.catch(x => { log(x); return 50; });
// 10 20 Error(30)
reject(new Error(10))
Promise.resolve(10)
.then(x => { log(x); return Promise.resolve(20); })
.then(x => { log(x); });
Promise.resolve(10)
.then(x => { log(x); return Promise.resolve(20); })
.then(x => { log(x); });
// 10 20
Promise.resolve(10)
.then(x => { log(x); return Promise.reject(new Error(20)); })
.then(x => { log('F', x); return 30; })
.catch(x => { log('R', x); return 40; })
.then(x => { log(x); });
Promise.resolve(10)
.then(x => { log(x); return Promise.reject(new Error(20)); })
.then(x => { log('F', x); return 30; })
.catch(x => { log('R', x); return 40; })
.then(x => { log(x); });
// 10 R Error: 20 40
fetch('https://api.com/users/42')
.then(response => response.json())
.then(user => fetch(`https://api.github.com/users/${user.name}`))
.then(response => response.json())
.then(user => new Promise((resolve, reject) => {
// check out users projects
resolve();
}));
Promise.all([
Promise.resolve(10),
20,
Promise.resolve(30),
]);
Promise.all([
Promise.resolve(10),
20,
Promise.resolve(30),
]);
// 10 20 30
const token = 'secret';
Promise.all([
fetch(`https://service-a.com/profile?token=${token}`)
.then(response => response.json())
.then(user => user.admin),
fetch(`https://service-b.com/profile?token=${token}`)
.then(response => response.json())
.then(user => user.admin),
fetch(`https://service-c.com/profile?token=${token}`)
.then(response => response.json())
.then(user => user.admin);
]);
const token = 'secret';
Promise.all([
fetch(`https://service-a.com/profile?token=${token}`)
.then(response => response.json()).then(user => user.admin)
.catch(error => { if (/**/) { return false; }});
fetch(`https://service-b.com/profile?token=${token}`)
.then(response => response.json()).then(user => user.admin)
.catch(error => { if (/**/) { return false; }});
fetch(`https://service-c.com/profile?token=${token}`)
.then(response => response.json()).then(user => user.admin)
.catch(error => { if (/**/) { return false; }});
]);
promises keep state
be mindful of promises chaining
catch returns fulfilled promise if error not rethrown
Promise.resolve(10).then(x => {
log(x);
return 20;
}).then(x => log(x));
Promise.resolve(30).then(x => {
log(x);
return 40;
}).then(x => log(x));
Promise.resolve(10).then(x => {
log(x);
return 20;
}).then(x => log(x));
Promise.resolve(30).then(x => {
log(x);
return 40;
}).then(x => log(x));
// 10 30 20 40
Promise.resolve(10).then(x => {
log(x);
return Promise.resolve(20);
}).then(x => log(x));
Promise.resolve(30).then(x => {
log(x);
return 40;
}).then(x => log(x));
Promise.resolve(10).then(x => {
log(x);
return Promise.resolve(20);
}).then(x => log(x));
Promise.resolve(30).then(x => {
log(x);
return 40;
}).then(x => log(x));
// 10 30 40 20
setTimeout(() => log('macro'), 0);
Promise.resolve().then(() => log('micro'));
log('current');
setTimeout(() => log('macro'), 0);
Promise.resolve().then(() => log('micro'));
log('current');
// current micro macro
Promise.resolve()
.then(() => {
setTimeout(() => log('timeout'), 0);
})
.then(() => {
log('promise');
});
Promise.resolve()
.then(() => {
setTimeout(() => log('timeout'), 0);
})
.then(() => {
log('promise');
});
// promise timeout
Promise.reject(new Error(10));
VM7904:1 Uncaught (in promise) Error: 10
at <anonymous>:1:16
try {
Promise.reject(new Error(10));
} catch (error) {
console.log('caught error'); // will not be logged
}
VM7997:2 Uncaught (in promise) Error: 10
at <anonymous>:2:20
window.addEventListener('unhandledrejection', (event) => {
console.log('unhandled', event.reason);
});
p = new Promise(() => {
throw new Error(20);
});
// unhandled Error: 20
window.addEventListener('unhandledrejection', (event) => {
console.log('unhandled', event.reason);
});
p = new Promise(() => {
throw new Error(20);
});
setTimeout(() => {
p.catch(e => console.log('handling', e));
}, 1000);
// unhandled Error 20
// handling Error 20
window.addEventListener('unhandledrejection', (event) => {
console.log('unhandled', event.reason);
});
window.addEventListener('rejectionhandled', (event) => {
console.log('handled rejected', event.reason);
});
p = new Promise(() => {
throw new Error(20);
});
setTimeout(() => {
console.log('will handle');
p.catch(e => console.log('handling', e));
console.log('handled');
}, 1000);
async function foo() {
return 1;
}
foo().then(x => log(x));
// 1
async function foo() {
return Promise.resolve(1);
}
foo().then(x => log(x));
// 1
p = new Promise((reject) => {
setTimeout(() => {
resolve(42);
}. 1000);
})
async function foo() {
log('before');
const result = await p();
log('after', result);
}
// before after 42
(async () => {
setTimeout(() => alert('timeout'), 0);
await f();
alert('after await');
})();
(async () => {
setTimeout(() => alert('timeout'), 0);
await f();
alert('after await');
})();
// after await timeout
async function prepareDinner(meatType = 'fish') {
const dinner = await prepareBaseDinner();
const meat = await selectMeat(meatType);
const wine = await selectWine(meat.getWineType());
dinner.addMeat(meat);
dinner.addWine(wine);
return dinner;
}
async function prepareDinner(meatType = 'fish') {
const dinner = await prepareBaseDinner();
const meat = await selectMeat(meatType);
const wine = await selectWine(meat.getWineType());
dinner.addMeat(meat);
dinner.addWine(wine);
return dinner;
}
// |-------dinner------->|---meat--->|---wine--->|
function prepareDinner(meatType = 'fish') {
const dinnerPromise = prepareBaseDinner();
const meatPromise = selectMeat(meatType);
const winePromise = meatPromise.then(meat => {
return selectWine(meat.getWineType());
});
return Promise.all([ dinnerPromise, meatPromise, winePromise ]).then(
([ dinner, meat, wine ]) => {
dinner.addMeat(meat);
dinner.addWine(wine);
return dinner;
}
);
}
function prepareDinner(meatType = 'fish') {
const dinnerPromise = prepareBaseDinner();
const meatPromise = selectMeat(meatType);
const winePromise = meatPromise.then(meat => {
return selectWine(meat.getWineType());
});
return Promise.all([ dinnerPromise, meatPromise, winePromise ]).then(
([ dinner, meat, wine ]) => {
dinner.addMeat(meat);
dinner.addWine(wine);
return dinner;
}
);
}
// |-------dinner------->|
// |---meat--->|---wine--->|
microtasks have priority over macrotasks
unhandled rejection can be monitored
mind handling unhandled rejections
async uses the same microtasks queue
async can execute synchronous code if not used correctly
Q & A
For bedtime readers
Explanation of promises and async/await with examples and problems to solve
https://javascript.info/async
Async/await performance caveats:
https://medium.com/@bluepnume/even-with-async-await-you-probably-still-need-p
romises-9b259854c161
THANK YOU
Mateusz Bryła

More Related Content

What's hot

Rich and Snappy Apps (No Scaling Required)
Rich and Snappy Apps (No Scaling Required)Rich and Snappy Apps (No Scaling Required)
Rich and Snappy Apps (No Scaling Required)
Thomas Fuchs
 
The Ring programming language version 1.5.1 book - Part 63 of 180
The Ring programming language version 1.5.1 book - Part 63 of 180The Ring programming language version 1.5.1 book - Part 63 of 180
The Ring programming language version 1.5.1 book - Part 63 of 180
Mahmoud Samir Fayed
 
The Ring programming language version 1.8 book - Part 74 of 202
The Ring programming language version 1.8 book - Part 74 of 202The Ring programming language version 1.8 book - Part 74 of 202
The Ring programming language version 1.8 book - Part 74 of 202
Mahmoud Samir Fayed
 
The Ring programming language version 1.7 book - Part 72 of 196
The Ring programming language version 1.7 book - Part 72 of 196The Ring programming language version 1.7 book - Part 72 of 196
The Ring programming language version 1.7 book - Part 72 of 196
Mahmoud Samir Fayed
 
Lisp
LispLisp
Lisp
Sam Lee
 
javascript function & closure
javascript function & closurejavascript function & closure
javascript function & closure
Hika Maeng
 
Extreme JavaScript Performance
Extreme JavaScript PerformanceExtreme JavaScript Performance
Extreme JavaScript Performance
Thomas Fuchs
 
The Ring programming language version 1.6 book - Part 71 of 189
The Ring programming language version 1.6 book - Part 71 of 189The Ring programming language version 1.6 book - Part 71 of 189
The Ring programming language version 1.6 book - Part 71 of 189
Mahmoud Samir Fayed
 
Orsiso
OrsisoOrsiso
Orsiso
e27
 
The Ring programming language version 1.10 book - Part 81 of 212
The Ring programming language version 1.10 book - Part 81 of 212The Ring programming language version 1.10 book - Part 81 of 212
The Ring programming language version 1.10 book - Part 81 of 212
Mahmoud Samir Fayed
 
The Ring programming language version 1.6 book - Part 69 of 189
The Ring programming language version 1.6 book - Part 69 of 189The Ring programming language version 1.6 book - Part 69 of 189
The Ring programming language version 1.6 book - Part 69 of 189
Mahmoud Samir Fayed
 
The Ring programming language version 1.4 book - Part 18 of 30
The Ring programming language version 1.4 book - Part 18 of 30The Ring programming language version 1.4 book - Part 18 of 30
The Ring programming language version 1.4 book - Part 18 of 30
Mahmoud Samir Fayed
 
The Ring programming language version 1.6 book - Part 68 of 189
The Ring programming language version 1.6 book - Part 68 of 189The Ring programming language version 1.6 book - Part 68 of 189
The Ring programming language version 1.6 book - Part 68 of 189
Mahmoud Samir Fayed
 
Node.js flow control
Node.js flow controlNode.js flow control
Node.js flow control
Simon Su
 
The Ring programming language version 1.5.1 book - Part 65 of 180
The Ring programming language version 1.5.1 book - Part 65 of 180The Ring programming language version 1.5.1 book - Part 65 of 180
The Ring programming language version 1.5.1 book - Part 65 of 180
Mahmoud Samir Fayed
 
The Ring programming language version 1.5.1 book - Part 51 of 180
The Ring programming language version 1.5.1 book - Part 51 of 180The Ring programming language version 1.5.1 book - Part 51 of 180
The Ring programming language version 1.5.1 book - Part 51 of 180
Mahmoud Samir Fayed
 
The Ring programming language version 1.3 book - Part 50 of 88
The Ring programming language version 1.3 book - Part 50 of 88The Ring programming language version 1.3 book - Part 50 of 88
The Ring programming language version 1.3 book - Part 50 of 88
Mahmoud Samir Fayed
 
The Ring programming language version 1.5.3 book - Part 77 of 184
The Ring programming language version 1.5.3 book - Part 77 of 184The Ring programming language version 1.5.3 book - Part 77 of 184
The Ring programming language version 1.5.3 book - Part 77 of 184
Mahmoud Samir Fayed
 
The Ring programming language version 1.8 book - Part 73 of 202
The Ring programming language version 1.8 book - Part 73 of 202The Ring programming language version 1.8 book - Part 73 of 202
The Ring programming language version 1.8 book - Part 73 of 202
Mahmoud Samir Fayed
 
The Ring programming language version 1.5.1 book - Part 62 of 180
The Ring programming language version 1.5.1 book - Part 62 of 180The Ring programming language version 1.5.1 book - Part 62 of 180
The Ring programming language version 1.5.1 book - Part 62 of 180
Mahmoud Samir Fayed
 

What's hot (20)

Rich and Snappy Apps (No Scaling Required)
Rich and Snappy Apps (No Scaling Required)Rich and Snappy Apps (No Scaling Required)
Rich and Snappy Apps (No Scaling Required)
 
The Ring programming language version 1.5.1 book - Part 63 of 180
The Ring programming language version 1.5.1 book - Part 63 of 180The Ring programming language version 1.5.1 book - Part 63 of 180
The Ring programming language version 1.5.1 book - Part 63 of 180
 
The Ring programming language version 1.8 book - Part 74 of 202
The Ring programming language version 1.8 book - Part 74 of 202The Ring programming language version 1.8 book - Part 74 of 202
The Ring programming language version 1.8 book - Part 74 of 202
 
The Ring programming language version 1.7 book - Part 72 of 196
The Ring programming language version 1.7 book - Part 72 of 196The Ring programming language version 1.7 book - Part 72 of 196
The Ring programming language version 1.7 book - Part 72 of 196
 
Lisp
LispLisp
Lisp
 
javascript function & closure
javascript function & closurejavascript function & closure
javascript function & closure
 
Extreme JavaScript Performance
Extreme JavaScript PerformanceExtreme JavaScript Performance
Extreme JavaScript Performance
 
The Ring programming language version 1.6 book - Part 71 of 189
The Ring programming language version 1.6 book - Part 71 of 189The Ring programming language version 1.6 book - Part 71 of 189
The Ring programming language version 1.6 book - Part 71 of 189
 
Orsiso
OrsisoOrsiso
Orsiso
 
The Ring programming language version 1.10 book - Part 81 of 212
The Ring programming language version 1.10 book - Part 81 of 212The Ring programming language version 1.10 book - Part 81 of 212
The Ring programming language version 1.10 book - Part 81 of 212
 
The Ring programming language version 1.6 book - Part 69 of 189
The Ring programming language version 1.6 book - Part 69 of 189The Ring programming language version 1.6 book - Part 69 of 189
The Ring programming language version 1.6 book - Part 69 of 189
 
The Ring programming language version 1.4 book - Part 18 of 30
The Ring programming language version 1.4 book - Part 18 of 30The Ring programming language version 1.4 book - Part 18 of 30
The Ring programming language version 1.4 book - Part 18 of 30
 
The Ring programming language version 1.6 book - Part 68 of 189
The Ring programming language version 1.6 book - Part 68 of 189The Ring programming language version 1.6 book - Part 68 of 189
The Ring programming language version 1.6 book - Part 68 of 189
 
Node.js flow control
Node.js flow controlNode.js flow control
Node.js flow control
 
The Ring programming language version 1.5.1 book - Part 65 of 180
The Ring programming language version 1.5.1 book - Part 65 of 180The Ring programming language version 1.5.1 book - Part 65 of 180
The Ring programming language version 1.5.1 book - Part 65 of 180
 
The Ring programming language version 1.5.1 book - Part 51 of 180
The Ring programming language version 1.5.1 book - Part 51 of 180The Ring programming language version 1.5.1 book - Part 51 of 180
The Ring programming language version 1.5.1 book - Part 51 of 180
 
The Ring programming language version 1.3 book - Part 50 of 88
The Ring programming language version 1.3 book - Part 50 of 88The Ring programming language version 1.3 book - Part 50 of 88
The Ring programming language version 1.3 book - Part 50 of 88
 
The Ring programming language version 1.5.3 book - Part 77 of 184
The Ring programming language version 1.5.3 book - Part 77 of 184The Ring programming language version 1.5.3 book - Part 77 of 184
The Ring programming language version 1.5.3 book - Part 77 of 184
 
The Ring programming language version 1.8 book - Part 73 of 202
The Ring programming language version 1.8 book - Part 73 of 202The Ring programming language version 1.8 book - Part 73 of 202
The Ring programming language version 1.8 book - Part 73 of 202
 
The Ring programming language version 1.5.1 book - Part 62 of 180
The Ring programming language version 1.5.1 book - Part 62 of 180The Ring programming language version 1.5.1 book - Part 62 of 180
The Ring programming language version 1.5.1 book - Part 62 of 180
 

Similar to Promise is a Promise

A promise is a Promise
A promise is a PromiseA promise is a Promise
A promise is a Promise
Mateusz Bryła
 
Better react/redux apps using redux-saga
Better react/redux apps using redux-sagaBetter react/redux apps using redux-saga
Better react/redux apps using redux-saga
Younes (omar) Meliani
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 
Un dsl pour ma base de données
Un dsl pour ma base de donnéesUn dsl pour ma base de données
Un dsl pour ma base de données
Romain Lecomte
 
ECMAScript 2015 Tips & Traps
ECMAScript 2015 Tips & TrapsECMAScript 2015 Tips & Traps
ECMAScript 2015 Tips & Traps
Adrian-Tudor Panescu
 
C++ Lambda and concurrency
C++ Lambda and concurrencyC++ Lambda and concurrency
C++ Lambda and concurrency
명신 김
 
Promise: async programming hero
Promise: async programming heroPromise: async programming hero
Promise: async programming hero
The Software House
 
$q and Promises in AngularJS
$q and Promises in AngularJS $q and Promises in AngularJS
$q and Promises in AngularJS
a_sharif
 
Angular2 rxjs
Angular2 rxjsAngular2 rxjs
Angular2 rxjs
Christoffer Noring
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
Domenic Denicola
 
Promises in iOS development
Promises in iOS developmentPromises in iOS development
Promises in iOS development
RomanPanichkin
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJS
Kyung Yeol Kim
 
Kitura Todolist tutorial
Kitura Todolist tutorialKitura Todolist tutorial
Kitura Todolist tutorial
Robert F. Dickerson
 
Pablo Magaz | ECMAScript 2018 y más allá | Codemotion Madrid 2018
Pablo Magaz | ECMAScript 2018 y más allá | Codemotion Madrid 2018Pablo Magaz | ECMAScript 2018 y más allá | Codemotion Madrid 2018
Pablo Magaz | ECMAScript 2018 y más allá | Codemotion Madrid 2018
Codemotion
 
ES6, WTF?
ES6, WTF?ES6, WTF?
ES6, WTF?
James Ford
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
Dmitry Sheiko
 
JavaScript Futures—ES2017 and Beyond
JavaScript Futures—ES2017 and BeyondJavaScript Futures—ES2017 and Beyond
JavaScript Futures—ES2017 and Beyond
Jeff Strauss
 
Managing State in React Apps with RxJS by James Wright at FrontCon 2019
Managing State in React Apps with RxJS by James Wright at FrontCon 2019Managing State in React Apps with RxJS by James Wright at FrontCon 2019
Managing State in React Apps with RxJS by James Wright at FrontCon 2019
DevClub_lv
 
Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0
Oscar Renalias
 
Promises are so passé - Tim Perry - Codemotion Milan 2016
Promises are so passé - Tim Perry - Codemotion Milan 2016Promises are so passé - Tim Perry - Codemotion Milan 2016
Promises are so passé - Tim Perry - Codemotion Milan 2016
Codemotion
 

Similar to Promise is a Promise (20)

A promise is a Promise
A promise is a PromiseA promise is a Promise
A promise is a Promise
 
Better react/redux apps using redux-saga
Better react/redux apps using redux-sagaBetter react/redux apps using redux-saga
Better react/redux apps using redux-saga
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
 
Un dsl pour ma base de données
Un dsl pour ma base de donnéesUn dsl pour ma base de données
Un dsl pour ma base de données
 
ECMAScript 2015 Tips & Traps
ECMAScript 2015 Tips & TrapsECMAScript 2015 Tips & Traps
ECMAScript 2015 Tips & Traps
 
C++ Lambda and concurrency
C++ Lambda and concurrencyC++ Lambda and concurrency
C++ Lambda and concurrency
 
Promise: async programming hero
Promise: async programming heroPromise: async programming hero
Promise: async programming hero
 
$q and Promises in AngularJS
$q and Promises in AngularJS $q and Promises in AngularJS
$q and Promises in AngularJS
 
Angular2 rxjs
Angular2 rxjsAngular2 rxjs
Angular2 rxjs
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
 
Promises in iOS development
Promises in iOS developmentPromises in iOS development
Promises in iOS development
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJS
 
Kitura Todolist tutorial
Kitura Todolist tutorialKitura Todolist tutorial
Kitura Todolist tutorial
 
Pablo Magaz | ECMAScript 2018 y más allá | Codemotion Madrid 2018
Pablo Magaz | ECMAScript 2018 y más allá | Codemotion Madrid 2018Pablo Magaz | ECMAScript 2018 y más allá | Codemotion Madrid 2018
Pablo Magaz | ECMAScript 2018 y más allá | Codemotion Madrid 2018
 
ES6, WTF?
ES6, WTF?ES6, WTF?
ES6, WTF?
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
JavaScript Futures—ES2017 and Beyond
JavaScript Futures—ES2017 and BeyondJavaScript Futures—ES2017 and Beyond
JavaScript Futures—ES2017 and Beyond
 
Managing State in React Apps with RxJS by James Wright at FrontCon 2019
Managing State in React Apps with RxJS by James Wright at FrontCon 2019Managing State in React Apps with RxJS by James Wright at FrontCon 2019
Managing State in React Apps with RxJS by James Wright at FrontCon 2019
 
Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0
 
Promises are so passé - Tim Perry - Codemotion Milan 2016
Promises are so passé - Tim Perry - Codemotion Milan 2016Promises are so passé - Tim Perry - Codemotion Milan 2016
Promises are so passé - Tim Perry - Codemotion Milan 2016
 

Recently uploaded

Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom KittEnhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Peter Caitens
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
Kubernetes at Scale: Going Multi-Cluster with Istio
Kubernetes at Scale:  Going Multi-Cluster  with IstioKubernetes at Scale:  Going Multi-Cluster  with Istio
Kubernetes at Scale: Going Multi-Cluster with Istio
Severalnines
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
sjcobrien
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
ShulagnaSarkar2
 
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data PlatformAlluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio, Inc.
 
What’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete RoadmapWhat’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete Roadmap
Envertis Software Solutions
 
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
kalichargn70th171
 
ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.
Maitrey Patel
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
brainerhub1
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
XfilesPro
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Paul Brebner
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
Tier1 app
 
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
widenerjobeyrl638
 
42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert
vaishalijagtap12
 
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
The Third Creative Media
 
Liberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptxLiberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptx
Massimo Artizzu
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
Bert Jan Schrijver
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
dakas1
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
Marcin Chrost
 

Recently uploaded (20)

Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom KittEnhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
Kubernetes at Scale: Going Multi-Cluster with Istio
Kubernetes at Scale:  Going Multi-Cluster  with IstioKubernetes at Scale:  Going Multi-Cluster  with Istio
Kubernetes at Scale: Going Multi-Cluster with Istio
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
 
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data PlatformAlluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
 
What’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete RoadmapWhat’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete Roadmap
 
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
 
ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
 
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
 
42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert
 
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
 
Liberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptxLiberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptx
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
 

Promise is a Promise

  • 1. By Mateusz Bryła Promise((resolve, reject) => { Math.random() > 0.5 ? resolve(love()) : reject(hate()); }).then(love => marry()).catch(hate => moveToAlaska());
  • 2. Let’s talk about JavaScript... https://www.destroyallsoftware.com/talks/wat ;)
  • 3. What are we even talking about? Promise Objects Introduced: ECMAScript 2015 (previously ES6) - June 2015 Spec: https://www.ecma-international.org/ecma-262/6.0/#sec-promise-objects Support: https://caniuse.com/#feat=promises Polyfills: - https://github.com/stefanpenner/es6-promise - http://bluebirdjs.com/docs/install.html Async / Await Introduced: ECMAScript 2017 - June 2017 Spec: https://www.ecma-international.org/ecma-262/8.0/#sec-async-function-definitions
  • 4. What are we even talking about? Promise Objects Introduced: ECMAScript 2015 (previously ES6) - June 2015 Spec: https://www.ecma-international.org/ecma-262/6.0/#sec-promise-objects Support: https://caniuse.com/#feat=promises
  • 5. What are we even talking about? Promise Objects Introduced: ECMAScript 2015 (previously ES6) - June 2015 Spec: https://www.ecma-international.org/ecma-262/6.0/#sec-promise-objects Support: https://caniuse.com/#feat=promises
  • 6. What are we even talking about? Promise Objects Introduced: ECMAScript 2015 (previously ES6) - June 2015 Spec: https://www.ecma-international.org/ecma-262/6.0/#sec-promise-objects Support: https://caniuse.com/#feat=promises
  • 7. What are we even talking about? Promise Objects Introduced: ECMAScript 2015 (previously ES6) - June 2015 Spec: https://www.ecma-international.org/ecma-262/6.0/#sec-promise-objects Support: https://caniuse.com/#feat=promises Polyfills: - https://github.com/stefanpenner/es6-promise - http://bluebirdjs.com/docs/install.html
  • 8. What are we even talking about? Promise Objects Introduced: ECMAScript 2015 (previously ES6) - June 2015 Spec: https://www.ecma-international.org/ecma-262/6.0/#sec-promise-objects Support: https://caniuse.com/#feat=promises Polyfills: - https://github.com/stefanpenner/es6-promise - http://bluebirdjs.com/docs/install.html Async / Await Introduced: ECMAScript 2017 - June 2017 Spec: https://www.ecma-international.org/ecma-262/8.0/#sec-async-function-definitions Support: https://caniuse.com/#feat=async-functions
  • 9. What are we even talking about? Promise Objects Introduced: ECMAScript 2015 (previously ES6) - June 2015 Spec: https://www.ecma-international.org/ecma-262/6.0/#sec-promise-objects Support: https://caniuse.com/#feat=promises Polyfills: - https://github.com/stefanpenner/es6-promise - http://bluebirdjs.com/docs/install.html Async / Await Introduced: ECMAScript 2017 - June 2017 Spec: https://www.ecma-international.org/ecma-262/8.0/#sec-async-function-definitions Support: https://caniuse.com/#feat=async-functions
  • 10. Promise “An object that is used as a placeholder for the eventual results of a deferred (and possibly asynchronous) computation” Promise p state is: - fulfilled if p.then(f,r) enqueues a job to call f - rejected if p.then(f,r) enqueues a job to call r - pending if not fulfilled not rejected - settled if not pending - resolved if settled or locked in to match state of a different promise
  • 11. function executeDelayed(operation, callback) { setTimeout(() => { try { const result = operation(); callback(null, result); } catch (error) { callback(error); } }, 1000); }
  • 12. function executeDelayed(operation, callback) { setTimeout(() => { try { const result = operation(); callback(null, result); } catch (error) { callback(error); } }, 1000); } executeDelayed(() => { return 42; }, (error, result) => { if (error) { console.log('delayed error', error); } else { console.error('delayed result', result); } });
  • 13. const promise = new Promise((resolve, reject) => { // perform action, call resolve / reject upon completion / error }); promise.then((result) => { // listen for completion }); promise.catch((error) => { // listen for error }); promise.finally(() => { // cleanup });
  • 14. function executeDelayed(operation, callback) { setTimeout(() => { try { const result = operation(); callback(null, result); } catch (error) { callback(error); } }, 1000); } function executeDelayed(operation) { return new Promise((resolve, reject) => { setTimeout(() => { try { const result = operation(); resolve(result); } catch (error) { reject(error); } }, 1000); }); }
  • 15. function executeDelayed(operation, callback) { setTimeout(() => { try { const result = operation(); callback(null, result); } catch (error) { callback(error); } }, 1000); } executeDelayed(() => { return 42; }, (error, result) => { if (error) { console.log('delayed error', error); } else { console.error('delayed result', result); } }); function executeDelayed(operation) { return new Promise((resolve, reject) => { setTimeout(() => { try { const result = operation(); resolve(result); } catch (error) { reject(error); } }, 1000); }); } executeDelayed(() => { return 42; }).then((result) => { console.log('delayed result, result); }).catch((error) => { console.error('delayed error', error); });
  • 16. function log() { console.log(...arguments); }
  • 17. p = new Promise((resolve, reject) => { resolve(10); }).then(x => log(x));
  • 18. p = new Promise((resolve, reject) => { resolve(10); }).then(x => log(x)); // 10
  • 19. p = new Promise((resolve, reject) => { reject(10); }).catch(x => log(x));
  • 20. p = new Promise((resolve, reject) => { reject(10); }).catch(x => log(x)); // 10
  • 21. p = new Promise((resolve, reject) => { resolve(10); resolve(20); }).then(x => log(x));
  • 22. p = new Promise((resolve, reject) => { resolve(10); resolve(20); }).then(x => log(x)); // 10
  • 23. p = new Promise((resolve, reject) => { resolve(10); reject(20); }).then(x => log('F', x)).catch(x => log('R', x));
  • 24. p = new Promise((resolve, reject) => { resolve(10); reject(20); }).then(x => log('F', x)).catch(x => log('R', x)); // 10
  • 25. p = new Promise((resolve, reject) => { reject(20); resolve(10); }).then(x => log('F', x)).catch(x => log('R', x));
  • 26. p = new Promise((resolve, reject) => { reject(20); resolve(10); }).then(x => log('F', x)).catch(x => log('R', x)); // 20
  • 27. const promise = new Promise((resolve, reject) => { // perform action, call resolve / reject upon completion / error }); promise.then((result) => { // listen for completion }); promise.catch((error) => { // listen for error }); promise.finally(() => { // cleanup });
  • 28. Promise.resolve(10); new Promise((resolve) => { resolve(10); }); Promise.reject(10); new Promise((resolve, reject) => { reject(10); }); // fulfills if all fulfilled, rejected otherwise Promise.all([Promise.resolve(10), Promise.reject(10)]); // resolves as first resolves Promise.race([Promise.resolve(10), Promise.reject(10)]);
  • 29. Promise.resolve(10) .then(x => log(x)) .then(x => log(x)) .then(x => log(x));
  • 30. Promise.resolve(10) .then(x => log(x)) .then(x => log(x)) .then(x => log(x)); // 10 undefined undefined
  • 31. p = Promise.resolve(10); p.then(x => log(x)); p.then(x => log(x)); p.then(x => log(x));
  • 32. p = Promise.resolve(10); p.then(x => log(x)); p.then(x => log(x)); p.then(x => log(x)); // 10 10 10
  • 33. Promise.resolve(10) .then(x => { log(x); return 20; }) .then(x => { log(x); return 30; }) .then(x => { log(x); });
  • 34. Promise.resolve(10) .then(x => { log(x); return 20; }) .then(x => { log(x); return 30; }) .then(x => { log(x); }); // 10 20 30
  • 35. Promise.resolve(10) .then(x => { log(x); return 20; }) .catch(x => { log(x); return 30; }) .then(x => { log(x); return 40; }) .then(x => { log(x); return 50; });
  • 36. Promise.resolve(10) .then(x => { log(x); return 20; }) .catch(x => { log(x); return 30; }) .then(x => { log(x); return 40; }) .then(x => { log(x); return 50; }); // 10 20 40
  • 37. Promise.reject(10) .catch(x => log(x)) .catch(x => log(x)) .catch(x => log(x));
  • 38. Promise.reject(10) .catch(x => log(x)) .catch(x => log(x)) .catch(x => log(x)); // 10
  • 39. Promise.reject(10) .catch(x => { log(x); return 20; }) .then(x => { log(x); return 30; }) .catch(x => { log(x); return 40; }) .then(x => { log(x); return 50; });
  • 40. Promise.reject(10) .catch(x => { log(x); return 20; }) .then(x => { log(x); return 30; }) .catch(x => { log(x); return 40; }) .then(x => { log(x); return 50; }); // 10 20 30
  • 41. Promise.resolve(10) .then(x => { log(x); return 20; }) .then(x => { log(x); throw new Error(30); }) .then(x => { log(x); return 40; }) .catch(x => { log(x); return 50; });
  • 42. Promise.resolve(10) .then(x => { log(x); return 20; }) .then(x => { log(x); throw new Error(30); }) .then(x => { log(x); return 40; }) .catch(x => { log(x); return 50; }); // 10 20 Error(30)
  • 44. Promise.resolve(10) .then(x => { log(x); return Promise.resolve(20); }) .then(x => { log(x); });
  • 45. Promise.resolve(10) .then(x => { log(x); return Promise.resolve(20); }) .then(x => { log(x); }); // 10 20
  • 46. Promise.resolve(10) .then(x => { log(x); return Promise.reject(new Error(20)); }) .then(x => { log('F', x); return 30; }) .catch(x => { log('R', x); return 40; }) .then(x => { log(x); });
  • 47. Promise.resolve(10) .then(x => { log(x); return Promise.reject(new Error(20)); }) .then(x => { log('F', x); return 30; }) .catch(x => { log('R', x); return 40; }) .then(x => { log(x); }); // 10 R Error: 20 40
  • 48. fetch('https://api.com/users/42') .then(response => response.json()) .then(user => fetch(`https://api.github.com/users/${user.name}`)) .then(response => response.json()) .then(user => new Promise((resolve, reject) => { // check out users projects resolve(); }));
  • 51. const token = 'secret'; Promise.all([ fetch(`https://service-a.com/profile?token=${token}`) .then(response => response.json()) .then(user => user.admin), fetch(`https://service-b.com/profile?token=${token}`) .then(response => response.json()) .then(user => user.admin), fetch(`https://service-c.com/profile?token=${token}`) .then(response => response.json()) .then(user => user.admin); ]);
  • 52. const token = 'secret'; Promise.all([ fetch(`https://service-a.com/profile?token=${token}`) .then(response => response.json()).then(user => user.admin) .catch(error => { if (/**/) { return false; }}); fetch(`https://service-b.com/profile?token=${token}`) .then(response => response.json()).then(user => user.admin) .catch(error => { if (/**/) { return false; }}); fetch(`https://service-c.com/profile?token=${token}`) .then(response => response.json()).then(user => user.admin) .catch(error => { if (/**/) { return false; }}); ]);
  • 53. promises keep state be mindful of promises chaining catch returns fulfilled promise if error not rethrown
  • 54. Promise.resolve(10).then(x => { log(x); return 20; }).then(x => log(x)); Promise.resolve(30).then(x => { log(x); return 40; }).then(x => log(x));
  • 55. Promise.resolve(10).then(x => { log(x); return 20; }).then(x => log(x)); Promise.resolve(30).then(x => { log(x); return 40; }).then(x => log(x)); // 10 30 20 40
  • 56. Promise.resolve(10).then(x => { log(x); return Promise.resolve(20); }).then(x => log(x)); Promise.resolve(30).then(x => { log(x); return 40; }).then(x => log(x));
  • 57. Promise.resolve(10).then(x => { log(x); return Promise.resolve(20); }).then(x => log(x)); Promise.resolve(30).then(x => { log(x); return 40; }).then(x => log(x)); // 10 30 40 20
  • 58. setTimeout(() => log('macro'), 0); Promise.resolve().then(() => log('micro')); log('current');
  • 59. setTimeout(() => log('macro'), 0); Promise.resolve().then(() => log('micro')); log('current'); // current micro macro
  • 60. Promise.resolve() .then(() => { setTimeout(() => log('timeout'), 0); }) .then(() => { log('promise'); });
  • 61. Promise.resolve() .then(() => { setTimeout(() => log('timeout'), 0); }) .then(() => { log('promise'); }); // promise timeout
  • 62. Promise.reject(new Error(10)); VM7904:1 Uncaught (in promise) Error: 10 at <anonymous>:1:16 try { Promise.reject(new Error(10)); } catch (error) { console.log('caught error'); // will not be logged } VM7997:2 Uncaught (in promise) Error: 10 at <anonymous>:2:20
  • 63. window.addEventListener('unhandledrejection', (event) => { console.log('unhandled', event.reason); }); p = new Promise(() => { throw new Error(20); }); // unhandled Error: 20
  • 64. window.addEventListener('unhandledrejection', (event) => { console.log('unhandled', event.reason); }); p = new Promise(() => { throw new Error(20); }); setTimeout(() => { p.catch(e => console.log('handling', e)); }, 1000); // unhandled Error 20 // handling Error 20
  • 65. window.addEventListener('unhandledrejection', (event) => { console.log('unhandled', event.reason); }); window.addEventListener('rejectionhandled', (event) => { console.log('handled rejected', event.reason); }); p = new Promise(() => { throw new Error(20); }); setTimeout(() => { console.log('will handle'); p.catch(e => console.log('handling', e)); console.log('handled'); }, 1000);
  • 66. async function foo() { return 1; } foo().then(x => log(x)); // 1 async function foo() { return Promise.resolve(1); } foo().then(x => log(x)); // 1
  • 67. p = new Promise((reject) => { setTimeout(() => { resolve(42); }. 1000); }) async function foo() { log('before'); const result = await p(); log('after', result); } // before after 42
  • 68. (async () => { setTimeout(() => alert('timeout'), 0); await f(); alert('after await'); })();
  • 69. (async () => { setTimeout(() => alert('timeout'), 0); await f(); alert('after await'); })(); // after await timeout
  • 70. async function prepareDinner(meatType = 'fish') { const dinner = await prepareBaseDinner(); const meat = await selectMeat(meatType); const wine = await selectWine(meat.getWineType()); dinner.addMeat(meat); dinner.addWine(wine); return dinner; }
  • 71. async function prepareDinner(meatType = 'fish') { const dinner = await prepareBaseDinner(); const meat = await selectMeat(meatType); const wine = await selectWine(meat.getWineType()); dinner.addMeat(meat); dinner.addWine(wine); return dinner; } // |-------dinner------->|---meat--->|---wine--->|
  • 72. function prepareDinner(meatType = 'fish') { const dinnerPromise = prepareBaseDinner(); const meatPromise = selectMeat(meatType); const winePromise = meatPromise.then(meat => { return selectWine(meat.getWineType()); }); return Promise.all([ dinnerPromise, meatPromise, winePromise ]).then( ([ dinner, meat, wine ]) => { dinner.addMeat(meat); dinner.addWine(wine); return dinner; } ); }
  • 73. function prepareDinner(meatType = 'fish') { const dinnerPromise = prepareBaseDinner(); const meatPromise = selectMeat(meatType); const winePromise = meatPromise.then(meat => { return selectWine(meat.getWineType()); }); return Promise.all([ dinnerPromise, meatPromise, winePromise ]).then( ([ dinner, meat, wine ]) => { dinner.addMeat(meat); dinner.addWine(wine); return dinner; } ); } // |-------dinner------->| // |---meat--->|---wine--->|
  • 74. microtasks have priority over macrotasks unhandled rejection can be monitored mind handling unhandled rejections async uses the same microtasks queue async can execute synchronous code if not used correctly
  • 75. Q & A
  • 76. For bedtime readers Explanation of promises and async/await with examples and problems to solve https://javascript.info/async Async/await performance caveats: https://medium.com/@bluepnume/even-with-async-await-you-probably-still-need-p romises-9b259854c161