diff --git a/lib/core.js b/lib/core.js index 2b576f7996e..a6270a7c71a 100644 --- a/lib/core.js +++ b/lib/core.js @@ -688,12 +688,16 @@ declare class Promise<+R> { static resolve(object: Promise | T): Promise; static reject(error: any): Promise; static all>(promises: T): Promise<$TupleMap>; + static allSettled>(promises: T): Promise<$TupleMap>; static race | T>(promises: Iterable): Promise; } // we use this signature when typing await expressions declare function $await(p: Promise | T): T; +declare function $settlement(p: Promise | T): SettlementResult; +declare type SettlementResult<+T> = {| status: 'fulfilled', +value: T |} | {| status: 'rejected', reason: mixed |}; + /* Binary data */ declare class ArrayBuffer { diff --git a/tests/core_tests/allSettled.js b/tests/core_tests/allSettled.js new file mode 100644 index 00000000000..fa3f8b6b3da --- /dev/null +++ b/tests/core_tests/allSettled.js @@ -0,0 +1,83 @@ +// @flow + +function* generator(): Iterable> { + while (true) { + yield Promise.resolve(1); + } +} + +let tests = [ + // good cases + function() { + let p1 : Promise<[]> = Promise.allSettled([]); + let p2 : Promise<[ + SettlementResult, + SettlementResult, + SettlementResult, + ]> = Promise.allSettled([1, '', false]); + let p3 : Promise<[ + SettlementResult, + SettlementResult, + SettlementResult, + ]> = Promise.allSettled([ + Promise.resolve(1), + Promise.resolve(''), + Promise.resolve(false), + ]); + let p4 : Promise<[ + SettlementResult, + SettlementResult, + ]> = Promise.allSettled([ + 1, + Promise.resolve(1), + ]); + let p5 : Promise<$ReadOnlyArray>> = Promise.allSettled(generator()); + + p5.then((results): Array => { + return results.map(result => { + if (result.status === 'fulfilled') { + return result.value; + } else { + return -1; + } + }); + }); + p5.then((results): Array => { + return results.map(result => { + if (result.status === 'rejected') { + return -1; + } else { + return result.value + } + }); + }); + }, + // wrong arguments + function() { + let p1 = Promise.allSettled(); + let p2 = Promise.allSettled(1); + let p3 = Promise.allSettled(Promise.resolve(1)); + }, + // wrong result type + function() { + let p1 : Promise = Promise.allSettled([]); + let p2 : Promise<[number, string, boolean]> = Promise.allSettled([1, '', false]); + let p3 : Promise<[number, string, boolean]> = Promise.allSettled([ + Promise.resolve(1), + Promise.resolve(''), + Promise.resolve(false), + ]); + }, + // wrong result handling + function() { + let p1 = Promise.allSettled(generator()); + + p1.then((results): Array => { + return results.map(result => result); + }); + + p1.then((results): Array => { + return results.map(result => result.value); + }); + }, +];