问题
I have 2 files in javascript.
One: main_app.js
import * as API from "./api.js";
const pin = API.getPin();
console.log(pin);
other is api.js
const baseUrl = "https://some.com/api";
export function getPin() {
try {
axios.post(baseUrl, { method: "pin" }).then((res) => console.log(res));
} catch {
console.log("Fail");
}
}
In the first file I need to save the output of the getPin() but I always get Promise - pending in the console. In the axios call and .then method I can console.log the correct data but whatever I try I am not able to return the data.
I have also tried async and await with no avail.
export async function getPin() {
try {
const res = await axios.post(baseUrl, { method: "pin" }).then(res => res.data);
return res.data;
} catch {
console.log("Fail");
}
}
I have tried class from es6 but with the same result and then thought I am probably not using the class correctly:
export class Api {
static baseUrl = "https://some.com/api";
static response = null;
static getPin() {
const body = { method: "pin" };
axios
.post(this.baseUrl, body)
.then((res) => (this.response = res.data))
.catch((err) => console.error(err));
}
}
I ve look at many articles and I am sure I am missing something obvious but I am losing my mind :-( Any help would be appreciated
EDIT: Not really a duplicate with suggested question.I have re-did the class and it looks like this
export default class API {
static baseUrl = "https://some.com/api";
static response = null;
static pin = null;
static getPin() {
axios
.post(this.baseUrl, { method: "pin" })
.then((res) => (this.pin = res.data.pin));
return this.pin;
}
}
but this will STILL not working as I need.Help please
回答1:
When using the async/await pattern with axios, .then is not needed. The await axios.post pauses the execution of code until the promise is resolved and returns the data from the API call, and thus allows for res.data to contain the response from the API. See below for a modified version of one of your examples:
export async function getPin() {
try {
// instead of this line:
// const res = await axios.post(baseUrl, { method: "pin" }).then(res => res.data);
// try the following, notice the .then() removed
const res = await axios.post(baseUrl, { method: "pin" });
// res contains the response from the API call, no need to use .then.
// you may want to console.log(res.data) out here instead to see what you get back first.
return res.data;
} catch(e) {
console.log("error: ", e);
}
}
In your main_app.js, you need to modify your code because API.getPin() is an asynchronous API call, that's why you're getting a promise.
import * as API from "./api.js";
let pinGlobal;
async function callAPIandSetPin() {
// must be awaited because API.getPin() is asynchronous.
const pin = await API.getPin();
console.log(pin);
// if you needed a global pin for whatever reason, you can modify it from here.
pinGlobal = pin;
}
callAPIandSetPin();
来源:https://stackoverflow.com/questions/64676433/axios-in-javascript-function-to-return-data