SlideShare uma empresa Scribd logo
1 de 77
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

Orsiso
OrsisoOrsiso
Orsiso
e27
 

Mais procurados (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
 

Semelhante a Promise is a Promise

Semelhante a 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
 

Último

introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Último (20)

Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
ManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide DeckManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide Deck
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 

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