0

I am trying to access a value from a service through a function, but it always return a Promise Object and not the value which I am returning. You can check the code below for details.

function testMtd(flag) {
  return fetch("apiURL", {
    method: "GET",
    json: true
  })
    .then((response) => {
      if (response.ok) {
        // console.log(response.json());
        return response.json();
      } else {
        alert(
          "Server returned " + response.status + " : " + response.statusText
        );
      }
    })
    .then((response) => {
      console.log(response.flag);
      return response.flag;
    })
    .catch((err) => {
      console.log(err);
    });
}

console.log("result: ", testMtd("IN"));

The result is always result: Promise {}

were as is should get the Flag URL from return

Phil
  • 157,677
  • 23
  • 242
  • 245
  • 1
    [`Promise.prototype.then()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then): _"The `then()` method returns a Promise."_ – Andreas Sep 23 '20 at 21:00
  • [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Andreas Sep 23 '20 at 21:01

1 Answers1

1

You can return value from "then" callback, but you have to realize it will fulfill the original Promise and return the Promise itself. You can't just synchronize asynchronous process. Therefore, you can access your value either by doing:

testMtd('IN').then((result) => console.log(result));

You can also declare your function testMtd as async:

async function testMtd(flag) { ... }

Then, in the context of other asynchronous method you can access the value the following way:

async function someFunction() {
    const result = await testMtd('IN');
}
John Smith
  • 401
  • 6
  • 17