Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Can't get Promise.all() to properly work

Hey all,

I'm trying to use Promise.all() to wait until an array of promises are resolved. Any JavaScript Promise pros out there? Here's a snippet of my code.

The .map method is properly working--executing over each array item in urlArray. But for some reason 'FINISHED!' is instantly logged to the terminal.

Maybe I'm not properly resolving in the scrapeShirtInformation() function?

Any thoughts would be very much appreciated. I've been trying to figure this out for day snow.

//more code above this
.then(function(urlArray){

  const v = urlArray.map(fn)

  Promise.all(v).then(console.log('FINISHED!'));
});
const fn = function scrapeShirtInformation(url){
  let finish = false;
  return new Promise((resolve, reject) => {
      request(url, function (error, response, body) {
        if (!error) {

          const $ = cheerio.load(body);

          let price = $('.price').text();
          let title = $(".shirt-details h1").text().substr(price.length + 1);
          let relativeImageUrl = $(".shirt-picture img").attr("src");
          let imageUrl = rootURL + relativeImageUrl;
          console.log('Writing data for: ' + url);

          let shirtInfo = {};
          shirtInfo.price = price;
          shirtInfo.title = title;
          shirtInfo.relativeImageUrl = relativeImageUrl;
          shirtInfo.imageUrl = imageUrl;

          //push shirt info into infoToWrite array
          infoToWrite.push(shirtInfo);

          console.log(infoToWrite);

          resolve(shirtInfo);
        } else {
            reject(console.log('FAIL!'));
            console.log(`An error was encountered: ${error.message}`);
        }
      });
    })
  }

1 Answer

Jose Soto
Jose Soto
23,407 Points

Try this:

Promise.all(v).then(values => {
  console.log("FINISHED");
});

Wow. I can't believe that's all it was! You're my hero.

Can you elaborate one what makes your code work by add values? Thank you so much!

Jose Soto
Jose Soto
23,407 Points

Glad I could help. The contents of the then chain needs to be a function. You can read the official documentation here.