{if(browser){ //returnawaitgetLang(document.documentElemen"> Access the return value of an asynchronous function using Svelte components-PHP Chinese Network Q&A
Access the return value of an asynchronous function using Svelte components
P粉463824410
P粉463824410 2023-08-16 00:11:05
0
1
496

I have the following code snippet (layout.svelte):

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); 

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 loadLang() 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粉463824410
P粉463824410

reply all (1)
P粉174151913

In markup, there isnative syntax (with many variations)that can be used to await promises:

{#await loadLang() then lang} {lang.someValue} {/await}

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}:

let lang; loadLang().then(l => lang = l);
{#if lang} {lang.someValue} {/if}

Having a guard onbrowseris not good. You may want to move the data loading into thelayoutloading functionso that it can be passed as adataattribute and can be used during SSR and CSR, and for Available on every page using layout.

Do not usedocument.documentElement.lang, instead use theAccept-Languageheader of the request on the server.

Loading data before the page is served/rendered also prevents potential layout changes or loading indicators.

    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!