-1

I try to get only the data of my fetch request but when i go out of my function there is a promise arround.

I try to fetch an API for starting a store in svelteJS but I'm wrong.


import {writable} from "svelte/store";

const getPokedex = async function () {
    let pokedexData
    await fetch('https://pokeapi.co/api/v2/pokemon?limit=100&offset=0')
        .then(response => response.json())
        .then(data => {
            pokedexData = createPokedex(data)
        })
    return pokedexData
}

const createPokedex = function (data) {
    let pokedex = writable(data)
    ...
}

export const pokedex = getPokedex();


SOLVED:


const getPokedex = async () => {
    const response = await fetch('https://pokeapi.co/api/v2/pokemon?limit=100&offset=0');
    const data = await response.json();
    let pokedex = data.results
    return createPokedex(pokedex);
}
export const pokedexStore = await getPokedex();
  • 2
    `async` function returns a Promise --- that's what it's designed to do - you can `export const pokedex = await getPokedex();` - also, the way you've written that getPkedex function is odd ... there's hardly ever a reason to use both async/await AND .then - that can be written simply like `const getPokedex = () => fetch('https://pokeapi.co/api/v2/pokemon?limit=100&offset=0').then(response => response.json()).then(createPokedex);` - note, no async/await there (I find this cleaner than using async/await with such simple code) – Jaromanda X Sep 20 '22 at 11:17
  • I didn't understand it in that way. Tjank you for your help :) – Alexis Van San Sep 20 '22 at 11:32
  • really? that's basically your code written without redundant async/await – Jaromanda X Sep 20 '22 at 11:37
  • I have tried with ``then`` but I have an error but the answer with async await have passed – Alexis Van San Sep 20 '22 at 13:20
  • 1
    you probably wrote it wrong – Jaromanda X Sep 20 '22 at 14:01

1 Answers1

0

Make use of async/await and try to not use then/catch while using async/await this will make your code more clean, readable, easy to work with

const getPokedex = async function () {
  const response = await fetch("https://pokeapi.co/api/v2/pokemon?limit=100&offset=0");
  const data = await response.json();
  return createPokedex(data);
};

this code will return the data you just have to wait for the promise using await

const pokedex = await getPokedex();

Sarkar
  • 1,225
  • 7
  • 21