You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
]).then(alert); // 1,2,3 when promises are ready: each promise contributes an array member
30
+
]).then(alert); // 1,2,3 când promisiunile sunt gata: fiecare promisiune contribuie cu un membru în array
31
31
```
32
32
33
-
Please note that the order of the resulting array members is the same as in its source promises. Even though the first promise takes the longest time to resolve, it's still first in the array of results.
33
+
Vă rugăm să notați că ordinea membrilor array-ului rezultat este aceeași cu cea din promisiunile sursă. Chiar dacă prima promisiune ia cel mai mult timp să se rezolve, ea este totuși prima în lista de rezultate.
34
34
35
-
A common trick is to map an array of job data into an array of promises, and then wrap that into`Promise.all`.
35
+
Un truc obișnuit este de a mapa un array cu date de sarcini într-un array cu promisiuni și apoi a le împacheta în`Promise.all`.
36
36
37
-
For instance, if we have an array of URLs, we can fetch them all like this:
37
+
De exemplu, dacă avem un array de URL-uri, le putem prelua pe toate în felul următor:
38
38
39
39
```js run
40
40
let urls = [
@@ -43,17 +43,17 @@ let urls = [
43
43
'https://api.github.com/users/jeresig'
44
44
];
45
45
46
-
//map every url to the promise of the fetch
46
+
//mapează fiecare url la promisiunea lui fetch
47
47
let requests =urls.map(url=>fetch(url));
48
48
49
-
// Promise.all waits until all jobs are resolved
49
+
// Promise.all așteaptă până când toate sarcinile sunt resolved
A bigger example with fetching user information for an array of GitHub users by their names (we could fetch an array of goods by their ids, the logic is identical):
56
+
Un exemplu mai amplu cu preluarea informațiilor utilizatorilor pentru un array de utilizatori GitHub după numele lor (am putea prelua un array de bunuri după id-urile lor, logica este identică):
57
57
58
58
```js run
59
59
let names = ['iliakan', 'remy', 'jeresig'];
@@ -62,47 +62,47 @@ let requests = names.map(name => fetch(`https://api.github.com/users/${name}`));
62
62
63
63
Promise.all(requests)
64
64
.then(responses=> {
65
-
//all responses are resolved successfully
65
+
//toate răspunsurile sunt rezolvate cu succes
66
66
for(let response of responses) {
67
-
alert(`${response.url}: ${response.status}`); //shows 200 for every url
67
+
alert(`${response.url}: ${response.status}`); //arată 200 pentru fiecare url
68
68
}
69
69
70
70
return responses;
71
71
})
72
-
//map array of responses into an array of response.json() to read their content
72
+
//mapează array de răspunsuri într-un array de response.json() pentru a citi conținutul lor
Here the second promise rejects in two seconds. That leads to an immediate rejection of`Promise.all`, so `.catch` executes: the rejection error becomes the outcome of the entire`Promise.all`.
92
+
Aici a doua promisiune este respinsă în două secunde. Asta duce la o respingere imediată a`Promise.all`, așa că se execută `.catch`: eroarea de respingere devine rezultatul întregii`Promise.all`.
93
93
94
-
```warn header="In case of an error, other promises are ignored"
95
-
If one promise rejects, `Promise.all` immediately rejects, completely forgetting about the other ones in the list. Their results are ignored.
94
+
```warn header="În cazul unei erori, celelalte promisiuni sunt ignorate"
95
+
Dacă o promisiune este respinsă, `Promise.all` se respinge imediat, uitând complet de celelalte din listă. Rezultatele acestora sunt ignorate.
96
96
97
-
For example, if there are multiple `fetch` calls, like in the example above, and one fails, the others will still continue to execute, but `Promise.all` won't watch them anymore. They will probably settle, but their results will be ignored.
97
+
De exemplu, dacă sunt mai multe apeluri `fetch`, ca în exemplul de mai sus, și unul eșuează, celelalte vor continua să se execute, dar `Promise.all` nu le va mai urmări. Probabil că se vor soluționa, dar rezultatele lor vor fi ignorate.
98
98
99
-
`Promise.all` does nothing to cancel them, as there's no concept of "cancellation" in promises. In [another chapter](info:fetch-abort) we'll cover `AbortController` that can help with that, but it's not a part of the Promise API.
99
+
`Promise.all` nu face nimic pentru a le anula, deoarece nu există conceptul de "anulare" în promisiuni. În [un alt capitol](info:fetch-abort) vom acoperi `AbortController` care poate ajuta cu asta, dar nu face parte din Promise API.
Normally, `Promise.all(...)`accepts an iterable (in most cases an array) of promises. But if any of those objects is not a promise, it's passed to the resulting array "as is".
În mod normal, `Promise.all(...)`acceptă un iterabil (în cele mai multe cazuri un array) de promisiuni. Dar dacă unul dintre aceste obiecte nu este o promisiune, este trecut în array-ul rezultat "așa cum este".
104
104
105
-
For instance, here the results are`[1, 2, 3]`:
105
+
De exemplu, aici rezultatele sunt`[1, 2, 3]`:
106
106
107
107
```js run
108
108
Promise.all([
@@ -114,31 +114,31 @@ Promise.all([
114
114
]).then(alert); // 1, 2, 3
115
115
```
116
116
117
-
So we are able to pass ready values to `Promise.all`where convenient.
117
+
Deci putem trece valori pregătite la `Promise.all`unde este convenabil.
118
118
````
119
119
120
120
## Promise.allSettled
121
121
122
122
[recent browser="new"]
123
123
124
-
`Promise.all` rejects as a whole if any promise rejects. That's good for "all or nothing" cases, when we need *all* results successful to proceed:
124
+
`Promise.all` se respinge în întregime dacă orice promisiune este respinsă. Acest lucru este bun pentru cazurile "totul sau nimic", când avem nevoie de *toate* rezultatele pozitive pentru a continua:
125
125
126
126
```js
127
127
Promise.all([
128
128
fetch('/template.html'),
129
129
fetch('/style.css'),
130
130
fetch('/data.json')
131
-
]).then(render); // render method needs results of all fetches
131
+
]).then(render); // metoda de randare are nevoie de rezultatele tuturor preluărilor
132
132
```
133
133
134
-
`Promise.allSettled` just waits for all promises to settle, regardless of the result. The resulting array has:
134
+
`Promise.allSettled` așteaptă doar ca toate promisiunile să fie soluționate, indiferent de rezultat. Array-ul rezultat are:
135
135
136
-
- `{status:"fulfilled", value:result}` for successful responses,
137
-
- `{status:"rejected", reason:error}` for errors.
136
+
- `{status:"fulfilled", value:result}` pentru răspunsurile reușite,
137
+
- `{status:"rejected", reason:error}` pentru erori.
138
138
139
-
For example, we'd like to fetch the information about multiple users. Even if one request fails, we're still interested in the others.
139
+
De exemplu, ne-ar plăcea să preluăm informații despre utilizatori multipli. Chiar dacă o cerere eșuează, încă suntem interesați de celelalte.
Rezultatele `results` din linia `(*)` de mai sus vor fi:
164
164
```js
165
165
[
166
166
{status: 'fulfilled', value: ...response...},
@@ -169,11 +169,11 @@ The `results` in the line `(*)` above will be:
169
169
]
170
170
```
171
171
172
-
So for each promise we get its status and `value/error`.
172
+
Deci pentru fiecare promisiune obținem statusul ei și `valoarea/error`.
173
173
174
174
### Polyfill
175
175
176
-
If the browser doesn't support `Promise.allSettled`, it's easy to polyfill:
176
+
Dacă browserul nu acceptă `Promise.allSettled`, este ușor să facem polyfill:
177
177
178
178
```js
179
179
if (!Promise.allSettled) {
@@ -188,91 +188,91 @@ if (!Promise.allSettled) {
188
188
}
189
189
```
190
190
191
-
In this code, `promises.map` takes input values, turns them into promises (just in case a non-promise was passed) with `p => Promise.resolve(p)`, and then adds `.then` handler to every one.
191
+
În acest cod, `promises.map` ia valorile de intrare, le transformă în promisiuni (doar în cazul în care a fost trecută o non-promisiune) cu `p => Promise.resolve(p)` și apoi adaugă gestionarul `.then` la fiecare dintre ele.
192
192
193
-
That handler turns a successful result `value` into `{status:'fulfilled', value}`, and an error `reason` into `{status:'rejected', reason}`. That's exactly the format of `Promise.allSettled`.
193
+
Acel gestionar schimbă un rezultat de succes `value` în `{status:'fulfilled', value}`, iar o eroare `reason` în `{status:'rejected', reason}`. Acesta este exact formatul lui `Promise.allSettled`.
194
194
195
-
Now we can use `Promise.allSettled` to get the results of *all* given promises, even if some of them reject.
195
+
Acum putem folosi `Promise.allSettled` pentru a obține rezultatele pentru *toate* promisiunile date, chiar dacă unele dintre ele sunt respinse.
196
196
197
197
## Promise.race
198
198
199
-
Similar to `Promise.all`, but waits only for the first settled promise and gets its result (or error).
199
+
Similar cu `Promise.all`, dar așteaptă doar prima promisiune soluționată și obține rezultatul (sau eroarea) acesteia.
200
200
201
-
The syntax is:
201
+
Sintaxa este:
202
202
203
203
```js
204
204
let promise = Promise.race(iterable);
205
205
```
206
206
207
-
For instance, here the result will be `1`:
207
+
De exemplu, aici rezultatul va fi `1`:
208
208
209
209
```js run
210
210
Promise.race([
211
211
new Promise((resolve, reject) => setTimeout(() => resolve(1), 1000)),
212
-
new Promise((resolve, reject) => setTimeout(() => reject(new Error("Whoops!")), 2000)),
212
+
new Promise((resolve, reject) => setTimeout(() => reject(new Error("Uuups!")), 2000)),
213
213
new Promise((resolve, reject) => setTimeout(() => resolve(3), 3000))
214
214
]).then(alert); // 1
215
215
```
216
216
217
-
The first promise here was fastest, so it became the result. After the first settled promise "wins the race", all further results/errors are ignored.
217
+
Prima promisiune de aici a fost cea mai rapidă, așa că a devenit rezultatul. După ce prima promisiune soluționată "câștigă cursa", toate celelalte rezultate/erori sunt ignorate.
218
218
219
219
220
220
## Promise.any
221
221
222
-
Similar to `Promise.race`, but waits only for the first fulfilled promise and gets its result. If all of the given promises are rejected, then the returned promise is rejected with [`AggregateError`](mdn:js/AggregateError) - a special error object that stores all promise errors in its `errors` property.
222
+
Similar cu `Promise.race`, dar așteaptă doar prima promisiune fulfilled și obține rezultatul acesteia. Dacă toate promisiunile date sunt respinse, atunci promisiunea returnată este respinsă cu [`AggregateError`](mdn:js/AggregateError) - un obiect special de eroare care stochează toate erorile promisiunii în proprietatea sa `errors`.
223
223
224
-
The syntax is:
224
+
Sintaxa este:
225
225
226
226
```js
227
227
let promise = Promise.any(iterable);
228
228
```
229
229
230
-
For instance, here the result will be `1`:
230
+
De exemplu, aici rezultatul va fi `1`:
231
231
232
232
```js run
233
233
Promise.any([
234
-
new Promise((resolve, reject) => setTimeout(() => reject(new Error("Whoops!")), 1000)),
234
+
new Promise((resolve, reject) => setTimeout(() => reject(new Error("Uuups!")), 1000)),
235
235
new Promise((resolve, reject) => setTimeout(() => resolve(1), 2000)),
236
236
new Promise((resolve, reject) => setTimeout(() => resolve(3), 3000))
237
237
]).then(alert); // 1
238
238
```
239
239
240
-
The first promise here was fastest, but it was rejected, so the second promise became the result. After the first fulfilled promise "wins the race", all further results are ignored.
240
+
Prima promisiune de aici a fost cea mai rapidă, dar a fost respinsă, așa că a doua promisiune a devenit rezultatul. După ce prima promisiune fulfilled "câștigă cursa", toate rezultatele ulterioare sunt ignorate.
241
241
242
-
Here's an example when all promises fail:
242
+
Iată un exemplu când toate promisiunile eșuează:
243
243
244
244
```js run
245
245
Promise.any([
246
-
new Promise((resolve, reject) => setTimeout(() => reject(new Error("Ouch!")), 1000)),
247
-
new Promise((resolve, reject) => setTimeout(() => reject(new Error("Error!")), 2000))
246
+
new Promise((resolve, reject) => setTimeout(() => reject(new Error("Au!")), 1000)),
247
+
new Promise((resolve, reject) => setTimeout(() => reject(new Error("Eroare!")), 2000))
As you can see, error objects for failed promises are available in the `errors` property of the `AggregateError` object.
255
+
După cum puteți vedea, obiectele de eroare pentru promisiunile eșuate sunt disponibile în proprietatea `errors` a obiectului `AggregateError`.
256
256
257
257
## Promise.resolve/reject
258
258
259
-
Methods `Promise.resolve` and `Promise.reject` are rarely needed in modern code, because `async/await` syntax (we'll cover it [a bit later](info:async-await)) makes them somewhat obsolete.
259
+
Metodele `Promise.resolve` și `Promise.reject` sunt rareori necesare în codul modern, deoarece sintaxa `async/await` (o vom acoperi [puțin mai târziu](info:async-await)) le face oarecum depășite.
260
260
261
-
We cover them here for completeness and for those who can't use `async/await` for some reason.
261
+
Le acoperim aici pentru completitudine și pentru cei care nu pot folosi `async/await` din anumite motive.
262
262
263
263
### Promise.resolve
264
264
265
-
`Promise.resolve(value)` creates a resolved promise with the result `value`.
265
+
`Promise.resolve(value)` creează o promisiune resolved cu rezultatul `value`.
266
266
267
-
Same as:
267
+
La fel ca și:
268
268
269
269
```js
270
270
let promise = new Promise(resolve => resolve(value));
271
271
```
272
272
273
-
The method is used for compatibility, when a function is expected to return a promise.
273
+
Metoda este utilizată pentru compatibilitate, atunci când se așteaptă ca o funcție să returneze o promisiune.
274
274
275
-
For example, the `loadCached` function below fetches a URL and remembers (caches) its content. For future calls with the same URL it immediately gets the previous content from cache, but uses `Promise.resolve` to make a promise of it, so the returned value is always a promise:
275
+
De exemplu, funcția `loadCached` de mai jos preia un URL și îi reține (caches) conținutul. Pentru apelurile viitoare cu același URL aceasta obține imediat conținutul anterior din cache, dar folosește `Promise.resolve` pentru a face o promisiune din acesta, așa că valoarea returnată este întotdeauna o promisiune:
276
276
277
277
```js
278
278
let cache = new Map();
@@ -293,31 +293,31 @@ function loadCached(url) {
293
293
}
294
294
```
295
295
296
-
We can write `loadCached(url).then(…)`, because the function is guaranteed to return a promise. We can always use `.then` after `loadCached`. That's the purpose of `Promise.resolve` in the line `(*)`.
296
+
Putem scrie `loadCached(url).then(…)`, deoarece funcția este garantată să returneze o promisiune. Putem folosi întotdeauna `.then` după `loadCached`. Acesta este scopul lui `Promise.resolve` din linia `(*)`.
297
297
298
298
### Promise.reject
299
299
300
-
`Promise.reject(error)` creates a rejected promise with `error`.
300
+
`Promise.reject(error)` creează o promisiune respinsă cu `error`.
301
301
302
-
Same as:
302
+
La fel ca:
303
303
304
304
```js
305
305
let promise = new Promise((resolve, reject) => reject(error));
306
306
```
307
307
308
-
In practice, this method is almost never used.
308
+
În practică, această metodă nu este aproape niciodată utilizată.
309
309
310
-
## Summary
310
+
## Sumar
311
311
312
-
There are 6 static methods of `Promise` class:
312
+
Sunt 6 metode statice ale clasei `Promise`:
313
313
314
-
1. `Promise.all(promises)` -- waits for all promises to resolve and returns an array of their results. If any of the given promises rejects, it becomes the error of `Promise.all`, and all other results are ignored.
315
-
2. `Promise.allSettled(promises)` (recently added method) -- waits for all promises to settle and returns their results as an array of objects with:
316
-
- `status`: `"fulfilled"` or `"rejected"`
317
-
- `value` (if fulfilled) or `reason` (if rejected).
318
-
3. `Promise.race(promises)` -- waits for the first promise to settle, and its result/error becomes the outcome.
319
-
4. `Promise.any(promises)` (recently added method) -- waits for the first promise to fulfill, and its result becomes the outcome. If all of the given promises are rejected, [`AggregateError`](mdn:js/AggregateError) becomes the error of `Promise.any`.
320
-
5. `Promise.resolve(value)` -- makes a resolved promise with the given value.
321
-
6. `Promise.reject(error)` -- makes a rejected promise with the given error.
314
+
1. `Promise.all(promises)` -- așteaptă ca toate promisiunile să se rezolve și returnează un array cu rezultatele lor. Dacă oricare dintre promisiunile date este respinsă, aceasta devine eroarea din `Promise.all`, iar toate celelalte rezultate sunt ignorate.
315
+
2. `Promise.allSettled(promises)` (metodă adăugată recent) -- așteaptă ca toate promisiunile să se soluționeze și returnează rezultatele lor ca un array de obiecte cu:
316
+
- `status`: `"fulfilled"` sau `"rejected"`.
317
+
- `value` (dacă sunt fulfilled) sau `reason` (dacă sunt rejected).
318
+
3. `Promise.race(promises)` -- așteaptă ca prima promisiune să se soluționeze, iar rezultatul/eroarea acesteia devine rezultatul.
319
+
4. `Promise.any(promises)` (metodă adăugată recent) -- așteaptă ca prima promisiune să fie fulfilled, iar rezultatul acesteia devine rezultatul. Dacă toate promisiunile date sunt respinse, [`AggregateError`](mdn:js/AggregateError) devine eroarea din `Promise.any`.
320
+
5. `Promise.resolve(value)` -- realizează o promisiune resolved cu valoarea dată.
321
+
6. `Promise.reject(error)` -- realizează o promisiune rejected cu eroarea dată.
322
322
323
-
Of all these, `Promise.all` is probably the most common in practice.
323
+
Dintre toate acestea, `Promise.all` este probabil cea mai comună în practică.
0 commit comments