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

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

问题描述:

我有一个预取反应应用程序资源的问题。我有一个函数,它应该获取json资源并将它们分配给循环中的对象属性。然后该函数应该返回已经解析完jsons的对象,而不是返回具有未解析promise的属性的对象。阻止js执行,直到异步请求完成

是否有可能停止执行js代码,直到承诺fullfiled所以该函数将返回正确的数据?

是的,就像是一个同步请求。

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

我不认为你应该使用像这样的地图来填充你更适合forEach的对象。虽然我不能保证这是问题所在。

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

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

    return r; 

}