Home > Mobile >  testing fastapi response to next.js with fetch, promise stuck in pending?
testing fastapi response to next.js with fetch, promise stuck in pending?

Time:05-05

my fetch is stuck in pending when I query a fastapi endpoint in local dev.

followed this blog and a few others - https://damaris-goebel.medium.com/promise-pending-60482132574d

Using this fetch code (having simplified it drastically just to get a simple solution working)

function fastapiRequest(path) {
    return fetch(`${path}`)
      .then((response) => {
        return response;
      }
      );

into a constant variable i.e.,

const xxxx = fastapiRequest(
    `http://0.0.0.0:8008/xcascasc/Dexaa/Emo.json?Magic=Dexxaa&emotion=expressions`
  );

Ideally I want to use UseSWR to do this as I'm using next.js, but first of all, just need it to work :)

A postman query like this works fine to return a value

curl --location --request GET 'http://0.0.0.0:8008/xcaxc/dexxa/emo.json?analysis=statistical&substance=dexxa&emo=powa' \
--header 'x_token: 13wdxaxacxasdc1'

the value is left like this in console.log

data show here? Promise {<pending>}

With the initial response being

Response {type: 'cors', url: 'url', redirected: false, status: 200, ok: true, …}

CodePudding user response:

first you need to parse the response into json if it's a json API.

function fastapiRequest(path) {
    return fetch(`${path}`)
      .then((response) => {
        return response.json();
       });
}

you need to 'await' for the rsponse

you need to write the below code in an async function

const xxxx = await fastapiRequest(
    `http://0.0.0.0:8008/xcascasc/Dexaa/Emo.json?Magic=Dexxaa&emotion=expressions`
  );

When you make an http request using fetch in javascript it will return a Promise, it's not stuck it's just need to be resloved, you can resolve it just like the above code with async await, or you can use the .then(() => { /* code... */ }) function, you can also use .catch(() => { /* handle error... */ }) function to handle errors.

CodePudding user response:

As per Documentation

The Response object, in turn, does not directly contain the actual JSON response body but is instead a representation of the entire HTTP response. So, to extract the JSON body content from the Response object, we use the json() method, which returns a second promise that resolves with the result of parsing the response body text as JSON.

.json() is an async method (it returns a Promise itself), so you have to assign the parsed value in the next .then(). So your code can be changed like this.

function fastApiRequest(path) {
    let res;
    fetch(`${path}`)
    .then((response) => response.json())
    .then((data) => (res = data))
    .then(() => console.log(res));
    
    return res;
}

response =  fastApiRequest('https://proton.api.atomicassets.io/atomicassets/v1/accounts?limit=10');
console.log('response')

If you want to use async/await approach, below is the code.

async function fastApiRequest(path) {
  try {
    const response = await fetch(path);
    const data = await response.json();
    return data;
  } catch (error) {
    console.error(error);
  }
}

async function test() {
  console.log(await fastApiRequest('https://proton.api.atomicassets.io/atomicassets/v1/accounts?limit=10'))
}
test()

  • Related