forked from stackblitz-labs/bolt.diy
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Avoid top level await to fix execution and full module initialization…
… race condition
- Loading branch information
Showing
3 changed files
with
106 additions
and
34 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
type SuspenseRecord<T> = | ||
| { | ||
status: 'resolved'; | ||
value: T; | ||
} | ||
| { | ||
status: 'rejected'; | ||
error: Error; | ||
} | ||
| { | ||
status: 'pending'; | ||
promise: Promise<T>; | ||
}; | ||
|
||
export function createAsyncSuspenseValue<T>(getValue: () => Promise<T>) { | ||
let record: SuspenseRecord<T> | undefined; | ||
|
||
const load = () => { | ||
const promise = getValue().then( | ||
(value) => { | ||
record = { status: 'resolved', value }; | ||
return value; | ||
}, | ||
(error) => { | ||
record = { status: 'rejected', error }; | ||
throw error; | ||
}, | ||
); | ||
|
||
record = { status: 'pending', promise }; | ||
return promise; | ||
}; | ||
|
||
const asyncValue = { | ||
read() { | ||
if (!record) { | ||
throw load(); | ||
} | ||
|
||
switch (record.status) { | ||
case 'pending': | ||
throw record.promise; | ||
case 'resolved': | ||
return record.value; | ||
case 'rejected': | ||
throw record.error; | ||
} | ||
}, | ||
preload() { | ||
if (record) { | ||
return; | ||
} | ||
load().catch(() => {}); | ||
}, | ||
}; | ||
|
||
return asyncValue; | ||
} |