0

I know its may be dumb question, I've already read similar questions. Tryed to do this but it not work at all in my code. I got function

const request = async (url) => {
  const response = await fetch(url);
  const result = await response.json();
  return result;
}

it return another promise

Promise {<pending>}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Array(100)

I need "array" NOT "promise". Tried to use Promise.resolve() but looks like I have no idea how to use it here.. all my attempts not work. always get error "resolve is not defined". Please just help if you know how to do it.

Will Black
  • 350
  • 2
  • 17

2 Answers2

2

Here is a working example of how this might work end to end:

const request = async (url) => {
  const response = await fetch(url);
  return response.json(); // no need to await the parsing of json
}

// now we call the function, I'm using a self-invoking function here but I assume you will run this code in your own function. Just make sure it's also an `async` function.
(async () => {
  const yourData = await request('https://bronzies.com/api/version');
  // we have to await the async function to resolve before we can see the data
  console.log(yourData);
})();

Another way to get the data out is to use then instead of async/await

request('https://bronzies.com/api/version')
  .then( yourData => console.log(yourData))
  .catch( error => console.error(error));

Hope this helps

Dominik
  • 6,078
  • 8
  • 37
  • 61
  • thank you. it works. I got some another error "Uncaught ReferenceError: yourData is not defined" but I think its becouse other my code. and finaly I got needed array in console. p.s. can't use ```.than``` becouse of the some bugs. – Will Black Mar 19 '20 at 22:05
  • Sure. happy it works now. Remember to mark the correct answer as `correct` :) – Dominik Mar 19 '20 at 22:06
1

You don't need to call await again. The first await does resolve the promise, and then response.json() parses the json and returns it as resolved

const request = async (url) => {
  const response = await fetch(url);
  return response.json();
}

Calling the above function:

const results = await request(url)
console.log(results)

OR

request(url).then(results => console.log(results))
Devon Norris
  • 180
  • 1
  • 12
  • tryed this, it still return the same result - promise. – Will Black Mar 19 '20 at 21:53
  • How are you calling this function? Async functions return a promise, so you will have to use await or .then wherever you call this. I will edit my answer to show an example – Devon Norris Mar 19 '20 at 22:00