Access the return value of an asynchronous function using Svelte components
P粉463824410
2023-08-16 00:11:05
<p>I have the following code snippet (layout.svelte): </p>
<pre class="brush:js;toolbar:false;">import { getLang } from "$lib/locale";
import { browser } from "$app/environment";
const loadLang = async () => {
if (browser) {
// return await getLang(document.documentElement.lang, "home").then( function (data: any) {
// const nav = JSON.stringify(data.nav);
// console.log(nav)
// return nav;
// });
const initLocale= await getLang(document.documentElement.lang, "home");
return initLocale.json();
}
};
const a = loadLang();
console.log(a);
</pre>
<p>The purpose of this code is to detect the browser language and the route of the request, and then search for the correct JSON file corresponding to the language and page. But there is a problem, I cannot access the language data of the async <code>loadLang()</code> in order to use it in the HTML element of the component, except in many answers mentioned here (which is not what I'm looking for) , what I want is a way to access the return value of the above function and use it in an HTML element? </p>
In markup, there is native syntax (with many variations) that can be used to await promises:
Another option is to declare a variable in the top scope and set it after the data is loaded. Of course it will be undefined at first, or whatever other value you initialize it to. Then usually combined with
{#if}
:Having a guard on
browser
is not good. You may want to move the data loading into thelayout
loading function so that it can be passed as adata
attribute and can be used during SSR and CSR, and for Available on every page using layout.Do not use
document.documentElement.lang
, instead use theAccept-Language
header of the request on the server.Loading data before the page is served/rendered also prevents potential layout changes or loading indicators.