【问题标题】:How to use Async/Await in this case?在这种情况下如何使用 Async/Await?
【发布时间】:2019-12-04 21:58:35
【问题描述】:

我有一个 index.js,它从 json 文件中获取数据。
我将此函数导出到我的 App.js,我想在其中将此数据存储在另一个对象中。

配置/index.js:

let config = (async () => {
    let data;
    if (process.env.NODE_ENV !== 'development') {
        if (
            typeof window !== 'undefined' &&
            (window.location.hostname.match('localhost') || window.location.hostname.match('127.0.0.1'))
        ) {
            data = require('./config.client.local.json');
        } else {
            data = require('./config.client.ip.json');
        }
    } else {
        data = fetch(process.env.PUBLIC_URL + "/config.client.json")
            .then(async res => await res.json());
    }
    return Object.assign({}, await data);
})();

export default config;

App.js

 import OIDC from 'oidc-client';
 import config from './configurations';
 window["UserManager"] = new OIDC.UserManager(config.oidc);

我不知道如何在不使用 async/await 的情况下获取数据

有人有想法吗?

【问题讨论】:

  • .then(res => res.json()); don't mix async/await with Promises,这是多余和混乱的。
  • 另外,你的配置是一个承诺,即使你使用async/await,所以你要么使用config.then(realConfigData => /* */)要么使用await config
  • @EmileBergeron,有没有办法让我可以在不使用 fetch 的情况下获取这个文件(文件在 src 之外)?
  • 根据您的项目配置,您有可能只需 import jsonConfig from '../config.client.json'; 并在构建时解析一次。

标签: javascript reactjs async-await fetch openid-connect


【解决方案1】:

看起来configPromise,这意味着您可以这样做:

config.then(({ oidc }) => {
  window.UserManager = new OIDC.UserManager(oidc);
});

【讨论】:

  • window.UserManager,括号语法不是必须的。
  • @EmileBergeron 是的,没错,我已经编辑了答案
  • 它也可能是 config.then(({ oidc }),因为它看起来像 oidcconfig 的属性,基于 OP 正在尝试做的事情。
猜你喜欢
  • 2022-01-23
  • 1970-01-01
  • 2020-03-15
  • 1970-01-01
  • 2022-11-15
  • 2013-05-02
  • 1970-01-01
  • 2018-12-04
  • 2017-09-08
相关资源
最近更新 更多