使用承诺运行 Cheerios 的异步调用

Run an asynchronous call of Cheerios with a Promise

本文关键字:异步 调用 Cheerios 运行 承诺      更新时间:2023-09-26

我有一个承诺调用,应该执行以下操作:

1)从已完成的链接中获取链接

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

现在,它不会在开始下一个任务之前完成每个任务,而是在完成任何操作之前完成。

由于我看不到您的代码中什么是异步的,因此这里有一个通用模式,可以使用 promise 和 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());

你会感兴趣的是"你的代码放在这里"的地方 - 这是你应该放置代码的地方。返回值必须是异步操作完成时解析

的承诺