up
This commit is contained in:
parent
d184bf8a98
commit
5d1813b115
30 changed files with 647 additions and 17128 deletions
53
8-async/05-promise-api/article.md
Normal file
53
8-async/05-promise-api/article.md
Normal file
|
@ -0,0 +1,53 @@
|
|||
# Promise API
|
||||
|
||||
There are helpful static methods in the `Promise` class. There are only 4 of them, so we'll quickly cover them here.
|
||||
|
||||
## Promise.all
|
||||
|
||||
The method to run many promises in parallel and wait till all of them are ready.
|
||||
|
||||
The syntax is:
|
||||
|
||||
```js
|
||||
let promise = Promise.all(iterable);
|
||||
```
|
||||
|
||||
It takes an `iterable` object with promises, for instance an array and returns a new promise that resolves with the array of their results when all of them are settled, or rejects with the first encountered error if any.
|
||||
|
||||
For instance:
|
||||
|
||||
```js run
|
||||
// loads 3 scripts in parallel and returns an array of them
|
||||
Promise.all([
|
||||
loadScript('/article/promise-api/one.js'),
|
||||
loadScript('/article/promise-api/two.js'),
|
||||
loadScript('/article/promise-api/three.js')
|
||||
]).then(scripts => {
|
||||
alert(`scripts loaded: ${scripts}`);
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
|
||||
- the returned `promise` awaits for al
|
||||
|
||||
In the previous chapter we saw how to run things sequentially. Promises also
|
||||
|
||||
- Promise.all
|
||||
- Promise.race
|
||||
- Promise.reject
|
||||
- Promise.resolve
|
||||
|
||||
Let's meet more functions and methods for promises.
|
||||
|
||||
|
||||
|
||||
Keywords `async` and `await` provide a more elegant way to write the code using promises.
|
||||
|
||||
## Async functions
|
||||
|
||||
The `async` function is like a regular one, but it wraps a returned value in a `Promise`.
|
||||
|
||||
|
||||
|
||||
Nowadays, promises are de-facto standard for asynchronous actions, when we need to
|
13
8-async/05-promise-api/head.html
Normal file
13
8-async/05-promise-api/head.html
Normal file
|
@ -0,0 +1,13 @@
|
|||
<script>
|
||||
function loadScript(src) {
|
||||
return new Promise(function(resolve, reject) {
|
||||
let script = document.createElement('script');
|
||||
script.src = src;
|
||||
|
||||
script.onload = () => resolve(script);
|
||||
script.onerror = () => reject(new Error("Script load error: " + src));
|
||||
|
||||
document.head.append(script);
|
||||
});
|
||||
}
|
||||
</script>
|
3
8-async/05-promise-api/one.js
Normal file
3
8-async/05-promise-api/one.js
Normal file
|
@ -0,0 +1,3 @@
|
|||
function one() {
|
||||
alert(1);
|
||||
}
|
3
8-async/05-promise-api/three.js
Normal file
3
8-async/05-promise-api/three.js
Normal file
|
@ -0,0 +1,3 @@
|
|||
function three() {
|
||||
alert(3);
|
||||
}
|
3
8-async/05-promise-api/two.js
Normal file
3
8-async/05-promise-api/two.js
Normal file
|
@ -0,0 +1,3 @@
|
|||
function two() {
|
||||
alert(2);
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue