简体   繁体   中英

block js execution until async request is completed

I have a problem with prefetching resources for react app. I have a function which should fetch json resources and assign them to a object properties in a loop. The function should then return the object with jsons allready resolved, but instead of it returns the object with properties as unresolved promises.

Is it possible to stop executing js code until the promises are fullfiled so the function will return correct data ?

Yes, something like a synchronous request.

async function getJson (file, url) {

  const response = await fetch(`${url}/${file}.json`);
  const json = await response.json();

  return json;
}

async function getTranslations(files, url) {
    let r = {};

  files.map( (file, i) => {
    r[file] = await getJson(file, url);
  });

  return r;
}

I don't think you should be using 'map' like that - to populate an object you're better with forEach. Though I couldn't guarantee that's the issue.

async function getTranslations(files, url) {
    let r = {};

    files.forEach(file => r[file] = await getJson(file, url));

    return r;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM