es.promise.all-settled.js
1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
'use strict';
var $ = require('../internals/export');
var call = require('../internals/function-call');
var aCallable = require('../internals/a-callable');
var newPromiseCapabilityModule = require('../internals/new-promise-capability');
var perform = require('../internals/perform');
var iterate = require('../internals/iterate');
// `Promise.allSettled` method
// https://tc39.es/ecma262/#sec-promise.allsettled
$({ target: 'Promise', stat: true }, {
allSettled: function allSettled(iterable) {
var C = this;
var capability = newPromiseCapabilityModule.f(C);
var resolve = capability.resolve;
var reject = capability.reject;
var result = perform(function () {
var promiseResolve = aCallable(C.resolve);
var values = [];
var counter = 0;
var remaining = 1;
iterate(iterable, function (promise) {
var index = counter++;
var alreadyCalled = false;
remaining++;
call(promiseResolve, C, promise).then(function (value) {
if (alreadyCalled) return;
alreadyCalled = true;
values[index] = { status: 'fulfilled', value: value };
--remaining || resolve(values);
}, function (error) {
if (alreadyCalled) return;
alreadyCalled = true;
values[index] = { status: 'rejected', reason: error };
--remaining || resolve(values);
});
});
--remaining || resolve(values);
});
if (result.error) reject(result.value);
return capability.promise;
}
});