0

I've been trying to fill an array with metadata that I collect with Xray, and haven't had any success. The function is called by an API route on my server and gets the links from my application.

I seem to be struggling with promises as it takes time to scrape the metadata, and I can't seem to get the function to wait until the data has been collected before moving on. Perhaps, I'm just not understanding how Xray works? Or maybe promises? I've tried everything I can think of, this being the most recent attempt (and the simplest):

  function createCollection() {
    Promise.all(rawLinks.map(function(link) {
      linksArray.push(xray(link, 'title')(function(error, title) {
        console.log(title);
        return title;
      }))
    }))
    .then(linksArray => {
      console.log(linksArray);
    });
  }

It's by far not the most robust or elaborate solution I've tried, but it's the most recent one. First the console logs an array with "undefined" as the data, THEN it logs the individual titles.

I would be very thankful for any help, or direction on what to research. Like I've said, I feel as if I've exhausted all my ideas and don't know where to even look anymore.

David Meents
  • 621
  • 4
  • 12
  • 1
    You must not push something to `linksArray` in that `map` callback, but just `return` a promise for one item. – Bergi Sep 09 '16 at 01:59
  • 1
    What promise library are you using? You'll need to [promisify](http://stackoverflow.com/q/22519784/1048572) the `xray` function. – Bergi Sep 09 '16 at 01:59

1 Answers1

0

Figured it out, this seems to be doing the trick!

  // format links into an array of objects
  var rawLinks = links.split(', ');
  var linksArray = [];

  createCollection();

  function createCollection() {
    rawLinks.map(function(link) {
      var fillMetaPromise = new Promise(
        function(resolve, reject) {
          var test = xray(link, 'title')(function(err, title) {
            var data = { title: title, link: link };
            resolve(data);
          });
        })
        .then(data => {
          processTitle(data.title, data.link);
        });
    });
  }

  function processTitle(title, link) {
    var object = {
      link: link,
      title: title
    };

    linksArray.push(object);
    console.log(linksArray);
  }
David Meents
  • 621
  • 4
  • 12