Disclaimer
This article is originally based on my understanding of this concept. No guarantee on the accuracy.😅
‘The Promise
object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.’
It was introduced to handle asynchronous operation like synchronous opeartion and avoid the callback hell.
1 | doSomething(function(result) { |
Common asynchronous-operation
- setTimeOut, setInterval
- XHR request (fetch api)
- Event Listening
Thansk to promise’s .then() chaining, we can put the callback outside:
1 | doSomething() |
*This all based on modern API that returning a promise. That is to say, the promise chains starts with an API function which returns a promise. *
We can create our own promise as well. Although it’s not typical practice but it can be helpful to ‘promisify’ some old callback-style API then chain the handler.
Let’s look at how a promise is created.
1 | var promise = new Promise( |
An example of wrapping a callback-style function with Promise:
1 | const wait = ms => new Promise(resolve => setTimeout(resolve, ms)); |
Another example to implement the query cache:
1 | function query(name) { |
Promise prototype method
- Promise.prototype.then()
- Promise.prototype.catch()
- Promise.prototype.finally()
Async & await
ES2017 🍬🍬🍬
1 | async function foo() { |
async
alone syntax can be used to create promise as well:
1 | async function foo(){ |
await
has to be used inside a async function.
await + < Promise > will wait the promise to be settled
Re-write the query search function in async await:
1 | async function mockAjax(name) { |
Promise queue implementation
- using forEach
1 | function doThing(fn, callback) { |
using reduce
1 | function queue(lists) { |
1 | function f2() { |
Other promise API
Promise.resolve()
- This one actually can be used to implement the .then() and .catch() api
- If the none parameter, return a resovled Promise with undefined value
- if the parameter is not a promise object, return a resovled Promise with that parameter
- If the parameter is a promise object, return that promise as it is.
Promise.reject()
- rarely used
Promise.race()
Promise.all(< iterable >)
usually work with .map()
p.then(results=>{ return Promise.all(results.map(r=> new Promise(resolve=>{ ...//do something }))) })
Reference: