First thing of first: Only in startup/init progress. I’m not trying find something to break the world.
I have do some research with js promise and await/async. And found something like this
Here is a demo in kotlin:
suspend fun readFile(path: Path) = withContext(Dispatchers.IO) {
Files.readString(path)
}!!
fun main() {
val runtimeInfo = runBlocking {
val config = readFile(Paths.get("config.properties")) // suspend async code
return@runBlocking MyFramework.RuntimeInfo.of(config) // Another async code
}
MyFramework.service(runtimeInfo) {
withContext(Dispatchers.IO) {
Files.readString(Paths.get("foo-bar"))
}
}
}
But in JS/TS, Things not that easy (BTW: I’m using Tauri + React):
new Promise((resolve, reject) => {
// Tauri invoke return a promise.
invoke('read_file', {path: 'config.json', defaultConfig: '{"version":1}'})
.then(it => resolve(it))
.catch(it => reject(it));
// ↑ This is really easy to make mistake (typo/forget)
// And this is really bad feeling with it: promise in promosie
}).then(it => {
const runtime = something(it as string);
ReactDOM.createRoot(document.getElementById("root")!!).render(
<React.StrictMode>
<App runtime={runtime}/>
</React.StrictMode>
);
}).catch((reject) => {
alert(reject);
});
Question: Is there any elegant way to archive async/sync conversion in JS/TS?