Replies: 4 comments 3 replies
-
If this is server code, you should avoid synchronous functions as much as possible once the server is handling requests. During the initial server startup, synchronous code is fine though. Synchronous code will block the event loop and prevent your server from doing anything else until the synchronous code completes (unless you're using multiple threads). Asynchronous functions will return a You should also try to avoid checking if something exists before using it (
The
You can use I would try rewriting your code to be something like this: try {
return cachedVersion(cacheDir)
} catch(err) {
render = renderSomething()
Deno.writeTextFile(cacheDir, render, {create: true})
return render
} |
Beta Was this translation helpful? Give feedback.
-
Yea, I'm not sure what your
Here are the docs for the asynchronous
Synchronous code is usually a tiny bit faster than asynchronous code because the asynchronous code has more overhead and state to maintain. However, you'd be trading a small amount of latency for a big throughput hit. A general rule of thumb is that if you ever need to do multiple things at once in a performant way (like serve HTTP requests) then you should avoid synchronous code. |
Beta Was this translation helpful? Give feedback.
-
Deno.readTextFile(cacheDir).then((res) => {
return <img href={cacheDir} />
}).catch(() => {
const render = render()
Deno.writeTextFile(cacheDir, render, {create: true})
return render
})
try { await Deno.stat(cacheDir)
return <img href={cacheDir} />
} catch(err) {
const render = render()
Deno.writeTextFile(cacheDir, render, {create: true})
return render
}
I tried both of these code, they worked but nothing was returned from my component, it was always empty (the file was created though) |
Beta Was this translation helpful? Give feedback.
-
(Apologies for being a bit late, but if you still care) You could create a new file via Deno.open(cachedDirectory, { createNew: true }).then(
// it wasn't cached
(file) => {
const renderResult = render();
file.write(renderResult);
return renderResult;
},
// it was cached
(_error) => <img href={cacheDir} />
); |
Beta Was this translation helpful? Give feedback.
-
Hi I'm still trying to understand if I got this correctly
I'm not sure why but the .stat async method works as well, what's really confusing me is the try catch statement instead of a simple if (fileExists(file). But anyway to my logic I need to do that in a sync way since on that it depends the result of the try and catch, while the creation of the cached version can happen in async while the server keeps preparing the response for the client.
Any suggestions to make this more clear?
Thanks
Beta Was this translation helpful? Give feedback.
All reactions