This commit is contained in:
Ilya Kantor 2017-05-22 14:18:43 +03:00
parent d184bf8a98
commit 5d1813b115
30 changed files with 647 additions and 17128 deletions

View 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

View 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>

View file

@ -0,0 +1,3 @@
function one() {
alert(1);
}

View file

@ -0,0 +1,3 @@
function three() {
alert(3);
}

View file

@ -0,0 +1,3 @@
function two() {
alert(2);
}