简体   繁体   中英

MeteorJS: Handling an async function inside another async function?

So, I'm lost on how to handle this properly.

What I want to do is:

// client side
Meteor.call("getData", url, function(images) {
  console.log(images); // get array of image src
});

// server side
Meteor.methods({
  "getData": (url) => {
      var images = [];
     // here is where I am lost
     // scrape the images
     scrape.request(url, function(err, $) {
       if (!err) {
          $('img').each(function(img) {
            let src = img.attribs.src;
            images.push(src);
          }
          // so at this point, I can console log an array on the server, but I need to bring it back to the client
       }
     } // now, how do I push all these and then signal to return the array?
   return images; // returns undefined, not waiting for all the data
   // I'm not sure how to wait for the array to be updated.
}});

Thoughts?

So, recap, I want to get an array back of all the image sources scraped from the website passed to the Meteor method.

There's a good tutorial on Meteor.wrapAsync that lays this out. Also this previous answer provides more details and explains error handling.

All the action happens on the server. In your case:

Meteor.methods({
  getData(url) => {
    const syncScrape = Meteor.wrapAsync(scrape.request);
    try {
      const $ = syncScrape(url,{});
      let images = [];
      $('img').each(img => {
        images.push(img.attribs.src);
      });
      return images;
    }
    catch(error) {
      throw new Meteor.error(error);
    }
  }
});

Also your client call needs to include an error from the callback:

Meteor.call("getData", url, (error, images) => {
  if (!error) console.log(images); // get array of image src
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM