javascript - meteor JS : Handling an async function inside another async function?

标签 javascript meteor ecmascript-6

所以,我不知道如何正确处理这个问题。

我想做的是:

// 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.
}});

想法?

所以,回顾一下,我想获取从传递给 Meteor 方法的网站中抓取的所有图像源的数组。

最佳答案

有一个很好的tutorialMeteor.wrapAsync这说明了这一点。另外this previous answer提供更多详细信息并解释错误处理。

所有操作都发生在服务器上。对于您的情况:

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);
    }
  }
});

您的客户端调用还需要包含回调中的错误:

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

关于javascript - meteor JS : Handling an async function inside another async function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43859591/

相关文章:

javascript - PHP 和 javascript 数组文字

javascript - 模板在 Meteor 中如何工作

javascript - 为什么 instanceof 在这里评估为真?

javascript - ES6 对象解构强制参数

node.js - 路由在 src/index.html 中不起作用

javascript - 使用 asp.net 在数据库中保存富文本编辑器文本时删除内联样式

javascript - jquery 中的自定义占位符

javascript - 用户单击元素时如何切换脚本的 src 属性?

date - meteor /JS 日期

MongoDB 各一