【问题标题】:Run an asynchronous call of Cheerios with a Promise使用 Promise 运行 Cheerios 的异步调用
【发布时间】:2016-01-28 22:51:02
【问题描述】:

我有一个承诺电话应该执行以下操作:

1) 从 completedLinks 中获取链接

2) 使用cheerio 将html 加载到$ 中,如jQuery。

3) 从页面中获取标题和其他详细信息

4) 将这些细节保存到对象siteObj

JS:

completedLinks = ["http://www.example.com/1","http://www.example.com/2","http://www.example.com/3"...]

   function fetchSiteDetails(arr) {
      return arr.reduce(function(promise, link) {
        console.log(link);
        var siteObj = {};

        var $ = cheerio.load(link);
        var titles = $("title").text().trim();  
        var html = $("#content").html().trim();
        var mainContent = $(".left-side").html().trim();
        var allLinks = $('a');

        siteObj.title = titles;
        siteObj.html = html;
        siteObj.mainContent = mainContent;
        siteObj.subPages = [];

       allLinks.each(function(i, elem) {
         siteObj.subPages.push($(this).attr('href'));
       });

        return promise;
      }, Promise.resolve());
    }

    fetchSiteDetails(completedLinks).then(function() {
        console.log('all done');
    });

现在它并没有在开始下一个任务之前完成每个任务,而是在完成任何事情之前完成。

【问题讨论】:

  • 您在 reduce 函数的每次迭代中都返回了一个已解决的承诺——reduce 代码的哪一部分完全是异步的,我无法从代码中分辨出来……@987654323 是什么@一个数组?

标签: javascript promise cheerio


【解决方案1】:

由于我在您的代码中看不到什么是异步的,因此这是一个使用 promises 和 array.reduce 串行运行异步操作的通用模式

return arr.reduce(function(promise, link) {
    return promise.then(function(resultOfPreviousPromise) {
        // your code goes here
        // return a promise that resolves when the asynchronous function completes
    });
}, Promise.resolve());

你会感兴趣的是“你的代码放在这里”的地方——你应该把你的代码放在哪里。返回值需要是异步操作完成时解析的promise

【讨论】:

    猜你喜欢
    • 2020-02-08
    • 2017-08-24
    • 1970-01-01
    • 2019-05-16
    • 1970-01-01
    • 2019-06-04
    • 1970-01-01
    • 2018-01-14
    • 1970-01-01
    相关资源
    最近更新 更多