es.promise.all-settled.js
1.48 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 aFunction = require('../internals/a-function');
var newPromiseCapabilityModule = require('../internals/new-promise-capability');
var perform = require('../internals/perform');
var iterate = require('../internals/iterate');
// `Promise.allSettled` method
// https://github.com/tc39/proposal-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 = aFunction(C.resolve);
var values = [];
var counter = 0;
var remaining = 1;
iterate(iterable, function (promise) {
var index = counter++;
var alreadyCalled = false;
values.push(undefined);
remaining++;
promiseResolve.call(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;
}
});