如何在 javascript 上导入和导出异步函数?
how to import and export asynchronous function on javascript?
我有这个异步函数
//example get
async getDatafromAPINODE(url) {
try {
let respond = await axios.get(API_URL_NODE + url, {
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + this.state.tokenUser,
},
});
if (respond.status >= 200 && respond.status < 300) {
console.log("respond Post Data", respond);
}
return respond;
} catch (err) {
let respond = err;
console.log("respond Post Data err", err);
return respond;
}
}
我怎样才能让这个函数可以导出?所以我可以在另一个文件中使用 import
好的,这就是我在做什么
//asyncFunction.js
export const getDatafromAPINODE = async (url, props) => {
try {
let respond = await axios.get(API_URL_NODE + url, {
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + props,
},
});
if (respond.status >= 200 && respond.status < 300) {
console.log("respond Post Data", respond);
}
return respond;
} catch (err) {
let respond = err;
console.log("respond Post Data err", err);
return respond;
}
};
然后我用
打电话
import {getDatafromAPINODE} from '../../../helper/asyncFunction'
如您所见,我使用了 2 个参数 url 和 props,这些 props 将用于获取我需要的令牌
我有这个异步函数
//example get
async getDatafromAPINODE(url) {
try {
let respond = await axios.get(API_URL_NODE + url, {
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + this.state.tokenUser,
},
});
if (respond.status >= 200 && respond.status < 300) {
console.log("respond Post Data", respond);
}
return respond;
} catch (err) {
let respond = err;
console.log("respond Post Data err", err);
return respond;
}
}
我怎样才能让这个函数可以导出?所以我可以在另一个文件中使用 import
好的,这就是我在做什么
//asyncFunction.js
export const getDatafromAPINODE = async (url, props) => {
try {
let respond = await axios.get(API_URL_NODE + url, {
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + props,
},
});
if (respond.status >= 200 && respond.status < 300) {
console.log("respond Post Data", respond);
}
return respond;
} catch (err) {
let respond = err;
console.log("respond Post Data err", err);
return respond;
}
};
然后我用
打电话import {getDatafromAPINODE} from '../../../helper/asyncFunction'
如您所见,我使用了 2 个参数 url 和 props,这些 props 将用于获取我需要的令牌