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