Promise function

dear all please can someone help me to fix the return function it return me undefined instead of the promise object it return me this message :
"Promise {}[[Prototype]]: Promise[[PromiseState]]: “fulfilled”[[PromiseResult]]: undefined
"
and this is my code :

 const getQuote =  async () => {
 return await fetch('https://type.fit/api/quotes').then(response=> response.json()).then(jsonResponse=> {
    if(!jsonResponse.length) {
       return
    }
    const indexQuote = Math.floor(Math.random() * jsonResponse.length)
    const quote = jsonResponse[indexQuote];
    return quote
 }).catch(e=> console.log(e))
 }
 getQuote().then((quote)=> console.log(quote))

Your code is working fine for me. Returns something like:

{text: 'There is only one way to happiness and that is…hings which are beyond the power of our will.', author: 'Epictetus'}

I wonder if you are having trouble reaching that URL. Can you get to it when directly accessing it through the browser? You could try inserting different console.log outputs to see where exactly things are failing.

1 Like

yes i do my friend alls works good within the code but when i try to execute my function to get for example the text inside the promise object it return me “undefined” i don’t know why.

If I understood your response correctly you mean that when you navigate to https://type.fit/api/quotes in your browser directly you do see the response list of quotes displayed. This would suggest your connection to that url is not being blocked.

It looks like your function is going to the empty return at the jsonResponse.length check. I suggest you add a more specific return like an error string, a more specific object like throwing an error, or rejecting the promise in this way:

      if (!jsonResponse.length) {
        return Promise.reject("JSON Response has no length: " + jsonResponse);
      }

That way you can confirm if this is where it is failing or if the undefined is somewhere else.

Do you have other code in your project besides what you posted at the top?

1 Like

thank you a lot my friend

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.