From 561cdd05a2a3b494c0d1a89354d8db66cf285826 Mon Sep 17 00:00:00 2001 From: Dan Abramov Date: Fri, 18 Jan 2019 21:16:02 +0000 Subject: [PATCH] Support sync thenables for lazy() (#14626) * Support sync thenables for lazy() * Don't commit twice --- .../src/ReactFiberLazyComponent.js | 6 +++++- .../src/__tests__/ReactLazy-test.internal.js | 17 +++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/packages/react-reconciler/src/ReactFiberLazyComponent.js b/packages/react-reconciler/src/ReactFiberLazyComponent.js index cae98e4a1f599..179262fa449c8 100644 --- a/packages/react-reconciler/src/ReactFiberLazyComponent.js +++ b/packages/react-reconciler/src/ReactFiberLazyComponent.js @@ -47,6 +47,7 @@ export function readLazyComponentType(lazyComponent: LazyComponent): T { lazyComponent._status = Pending; const ctor = lazyComponent._ctor; const thenable = ctor(); + lazyComponent._result = thenable; thenable.then( moduleObject => { if (lazyComponent._status === Pending) { @@ -73,7 +74,10 @@ export function readLazyComponentType(lazyComponent: LazyComponent): T { } }, ); - lazyComponent._result = thenable; + // Check if it resolved synchronously + if (lazyComponent._status === Resolved) { + return lazyComponent._result; + } throw thenable; } } diff --git a/packages/react-reconciler/src/__tests__/ReactLazy-test.internal.js b/packages/react-reconciler/src/__tests__/ReactLazy-test.internal.js index 80639c8831ba6..8fb4210f92923 100644 --- a/packages/react-reconciler/src/__tests__/ReactLazy-test.internal.js +++ b/packages/react-reconciler/src/__tests__/ReactLazy-test.internal.js @@ -61,6 +61,23 @@ describe('ReactLazy', () => { expect(root).toMatchRenderedOutput('Hi again'); }); + it('can resolve synchronously without suspending', async () => { + const LazyText = lazy(() => ({ + then(cb) { + cb({default: Text}); + }, + })); + + const root = ReactTestRenderer.create( + }> + + , + ); + + expect(ReactTestRenderer).toHaveYielded(['Hi']); + expect(root).toMatchRenderedOutput('Hi'); + }); + it('multiple lazy components', async () => { function Foo() { return ;