简体   繁体   English

阻止js执行,直到异步请求完成

[英]block js execution until async request is completed

I have a problem with prefetching resources for react app. 我在预取React应用程序资源时遇到问题。 I have a function which should fetch json resources and assign them to a object properties in a loop. 我有一个函数,应该获取json资源并将其分配给循环中的对象属性。 The function should then return the object with jsons allready resolved, but instead of it returns the object with properties as unresolved promises. 然后,该函数应返回所有已解析的jsons的对象,而不是返回具有未解决的Promise属性的对象。

Is it possible to stop executing js code until the promises are fullfiled so the function will return correct data ? 是否可以停止执行js代码,直到完全履行承诺,以便该函数将返回正确的数据?

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. 我不认为您应该使用“ map”这样的方法-用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;

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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