0

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

Jakub Koudela
  • 160
  • 1
  • 18
  • `export function getPin() {` function doesn't return anything – Jaromanda X Nov 04 '20 at 08:27
  • `export async function getPin()` function returns a Promise which will be the data (unless there's an error) – Jaromanda X Nov 04 '20 at 08:28
  • `static getPin() {` function doesn't return anything – Jaromanda X Nov 04 '20 at 08:28
  • Does this answer your question? [How do promises work in JavaScript?](https://stackoverflow.com/questions/18422021/how-do-promises-work-in-javascript) – ThisIsNoZaku Nov 04 '20 at 08:28
  • 1
    in all cases `const pin = API.getPin();` ... pin WILL be a Promise ... in the case of code 1 and 3, `undefined` - in the case of 2, the data you want will be resolved in that promise – Jaromanda X Nov 04 '20 at 08:29
  • As soon as a function returns a Promise (e.g. an `async` function) or by directly return ing a `Promise` there is no way to go back to a synchronous execution. `API.getPin()` returns a Promise and you need to use either `await` or `.then` to get the result. – t.niese Nov 04 '20 at 08:30
  • Get the pin from an async function in main_app and await getPin() –  Nov 04 '20 at 08:49
  • `axios` returns a Promise. A Promise is an object that promises to give you some value **in the future**. You **can't** have the value **now**. – Quentin Nov 04 '20 at 14:38
  • Yeah i think iam getting my head around axios and promises but still have no clue how to get the data out using the one function getPin().Man I'll pay you to help me out with this :-) Since 8am this morning – Jakub Koudela Nov 04 '20 at 14:41

1 Answers1

0

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();
James Ng
  • 136
  • 3
  • Hi, thanks for this, but this will still return a promise. Iam going crazy now :-) Don't understand why is it so complicated or I am still missing a big point. All I want is return data which are received from API – Jakub Koudela Nov 04 '20 at 10:34
  • @JakubKoudela, I just made an edit to further explain what you need to do. Does that help? – James Ng Nov 04 '20 at 18:44