【发布时间】:2020-11-19 17:19:38
【问题描述】:
我需要在 module.exports 上导出 axios 响应的结果。 这是我的代码:
brand.js
var axios = require('axios');
module.exports = (async function() {
try {
const { data } = axios.get('http://localhost:8000/api/v1/setting/index');
console.log(data.data.initial);
return {
name: data.data.name,
desc: data.data.description,
};
} catch (err) {
console.log(err);
}
})();
我尝试导入结果以用于另一个文件。 这是我的代码。
import React from 'react';
const {brand} = await require("brand.js");
class Dashboard extends Component {
render(){
const name = brand.name
const desc = brand.description;
return (
<h1>{title} | {description}</h1>
);
}
}
我的代码的结果是:
Can not use keyword 'await' outside an async function
这是浏览器上显示的错误:
如何解决这个问题?
【问题讨论】:
-
您是否尝试过将
await放在brand.js 中的axios.get()之前,而不是放在require()之前? -
这能回答你的问题吗? exporting after promise finishes
-
你必须在导入的(必需的)Promise 对象上使用
.then()。 -
我在axios前面加了await,但是错误依旧存在。
标签: javascript reactjs axios