Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

166
Views
Promise wont return valid value

I have this test I made just to check an API, but then i tryied to add an URL from a second fetch using as parameter a value obtained in the first fetch and then return a value to add in the first fecth. The idea is to add the image URL to the link. thanks in advance.

function script() {
    const url = 'https://pokeapi.co/api/v2/pokemon/?offset=20&limit=20'

    const result = fetch(url)
    .then( (res)=>{
        if(res.ok) {
            return res.json()
        } else {
            console.log("Error!!")
        }
    }).then( data => {
        console.log(data)

        const main = document.getElementById('main');

        main.innerHTML=`<p><a href='${data.next}'>Next</a></p>`;

        for(let i=0; i<data.results.length;i++){
            main.innerHTML=main.innerHTML+`<p><a href=${getImageURL(data.results[i].url)}>${data.results[i].name}</a></p>`;
        }

    })
}

 async function getImageURL(imgUrl) {
   
    const resultImg = await fetch(imgUrl)
        .then( (res)=> {
            return res.json()
        })
        .then (data => {
            console.log(data.sprites.other.dream_world.front_default);            
        })    
    return resultImg.sprites.other.dream_world.front_default;
}
    
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

In general, don't mix .then/.catch handlers with async/await. There's usually no need, and it can trip you up like this.

The problem is that your fulfillment handler (the .then callback) doesn't return anything, so the promise it creates is fulfilled with undefined.

You could return data, but really just don't use .then/.catch at all:

async function getImageURL(imgUrl) {
    const res = await fetch(imgUrl);
    if (!res.ok) {
        throw new Error(`HTTP error ${res.status}`);
    }
    const resultImg = await res.json();
    return resultImg.sprites.other.dream_world.front_default;
}

[Note I added a check of res.ok. This is (IMHO) a footgun in the fetch API, it doesn't reject its promise on HTTP errors (like 404 or 500), only on network errors. You have to check explicitly for HTTP errors. (I wrote it up on my anemic old blog here.)]

There's also a problem where you use getImageURL:

// Incorrent
for (let i = 0; i < data.results.length; i++) {
    main.innerHTML=main.innerHTML+`<p><a href=${getImageURL(data.results[i].url)}>${data.results[i].name}</a></p>`;
}

The problen here is that getImageURL, like all async functions, returns a promise. You're trying to use it as those it returned the fulfillment value you're expecting, but it can't — it doesn't have that value yet.

Instead, you need to wait for the promise(s) youre creating in that loop to be fulfilled. Since that loop is in synchronous code (not an async function), we'd go back to .then/.catch, and since we want to wait for a group of things to finish that can be done in parallel, we'd do that with Promise.all:

// ...
const main = document.getElementById('main');
const html = `<p><a href='${data.next}'>Next</a></p>`;
Promise.all(data.results.map(async ({url, name}) => {
    const realUrl = await getImageURL(url);
    return `<p><a href=${realUrl}>${name}</a></p>`;
}))
.then(paragraphs => {
    html += paragraphs.join("");
    main.innerHTML = html;
})
.catch(error => {
    // ...handle/report error...
});
about 4 years ago · Juan Pablo Isaza Report

0

For one, your

.then (data => {
            console.log(//...

at the end of the promise chain returns undefined. Just remove it, and if you want to console.log it, do console.log(resultImg) in the next statement/next line, after await.

about 4 years ago · Juan Pablo Isaza Report

0

This the final version that accomplish my goal. Just want to leave this just in case someone finds it usefull. Thanks for those who answer!

function script() {
    const url = 'https://pokeapi.co/api/v2/pokemon/?offset=20&limit=20'

    const result = fetch(url)
    .then( (res)=>{
        if(res.ok) {
            return res.json()
        } else {
            console.log("Error!!")
        }
    }).then( data => {
        console.log(data)

        const main = document.getElementById('main');

        main.innerHTML=`<p><a href='${data.next}'>Proxima Página</a></p>`;

        Promise.all(data.results.map(async ({url, name}) => {
            const realUrl = await getImageURL(url);
            return `<div><a href=${realUrl}>${name}</a></div>`;
        }))
        .then(paragraphs => {
            main.innerHTML=main.innerHTML+paragraphs;
        })
        .catch(error => {
            console.log(error);
        });
    })
}

 async function getImageURL(imgUrl) {
   
    const res = await fetch(imgUrl);

    if(!res.ok) {
        throw new Error(`HTTP Error ${res.status}`)
    } 
    
    const resultImg = await res.json();

    return resultImg.sprites.other.dream_world.front_default
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!