0

I have a promise object returned by an asynchronous function as it is shown bellow

function funcOne(data){
  let myArray = []
  fetch("/upload", {
     "method":"POST",
     "headers":{
        "Content-Type":"application/json; charset=utf-8"
     },
      "body":JSON.stringify(data)
    }).then(function(response){
        return response.text();
    }).then(function(data){
         myArray["error"] = data;
    });
    return myArray;
}

I want to obtain the stored value in myArray inside funcTwo

function funcTwo(data){
  let value = funcOne(data);
  console.log(value);

}

This is the output:

This is the output

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Oussama
  • 1
  • 1
  • "I have a promise object returned by" — The value of `myArray` is an array, not a promise. – Quentin Aug 21 '23 at 13:48
  • The promise result is stored in `myArray` – Oussama Aug 21 '23 at 13:49
  • That isn't the same thing as "returning a promise" and you don't store the result in that variable until **after** you've returned the original value. – Quentin Aug 21 '23 at 13:51
  • my issue is not the returned promise but the stored value of the later. I want to obtain the stored value inside `funcTwo` – Oussama Aug 21 '23 at 13:57
  • You want to use [await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await) then? – Peter Krebs Aug 21 '23 at 14:10
  • @Peter Krebs I already have the promise value stored inside `myArray`. what I want is to obtain the stored value in `myArray` inside `funcTwo`. look at the joined image – Oussama Aug 21 '23 at 14:22
  • I assumed fetch is asynchronous and may not complete immediately. Otherwise you have the output of the array in your image so why don't you simply try to access? It would be `value.error`. Also understand it is not an array technically, it is an object because you give it a named key. – Peter Krebs Aug 21 '23 at 14:52

0 Answers0