javascript - 链接功能作为 promise

标签 javascript node.js promise

我正在一个更大的应用程序中构建一个小 Node js 数据抓取功能。我对 Javascript 的 promise 不太满意,所以请原谅我的误解。不确定我的标题是否真的构成了我的问题。

所以我有这个:

const getAxiosUrls = function() { axios.get("http://localhost:3000/gatable")
  .then(function (response) {
      return urls = response.data.rows.map( ([x, y, z]) => y )
  })}

还有这个:

const getNbShares = function() {
    Promise.map(urls, requestPromise)
  .map((htmlOnePage, index) => {
    const $ = cheerio.load(htmlOnePage);
    const share = $('.nb-shares').html();
    let shareTuple = {};
    shareTuple[urls[index]] = share;
    return shareTuple;
  })
  .catch((e) => console.log('We encountered an error' + e));
}

我想这样做:

getAxiosUrls()
   .then(getNbShares)
   .then(res.json)

我尝试了一些东西,但大多数时候我遇到以下错误: 无法读取未定义的属性“then”。还要确保我的 getAxiosUrls 正常工作,我已经这样做了

getAxiosUrls()
setTimeout(function() {console.log(urls)},5000)

并且日志按预期返回响应。那我错过了什么?

最佳答案

函数 getAxiosUrlsgetNbShares 不返回 promise 。应该是

const getAxiosUrls = function() { 
    return axios.get("http://localhost:3000/gatable")
      .then(function (response) {
          return urls = response.data.rows.map( ([x, y, z]) => y )
    })
}

const getNbShares = function(urls) {
    return Promise.map(urls, requestPromise)
        .map((htmlOnePage, index) => {
            const $ = cheerio.load(htmlOnePage);
            const share = $('.nb-shares').html();
                let shareTuple = {};
                shareTuple[urls[index]] = share;
                return shareTuple;
        })
        .catch((e) => console.log('We encountered an error' + e));
}

附带说明:我建议删除 getNbShares 函数中的 .catch,因为这会导致此函数中返回的 promise 解析为 undefined 以防出现错误(您不会在 catch 处理程序中返回任何内容)。通常最好在 promise 链的最后添加错误处理,除非您可以采取措施从错误中恢复。

关于javascript - 链接功能作为 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39664511/

相关文章:

node.js - axios 授权 header /CORS 错误

javascript - 使用 Promise async/await 未定义

javascript - 使用 mocha.js 测试 jQuery.get 不起作用,其他 Deferred 也不起作用(RSVP)

javascript - for 循环内的 value.length 不起作用。 Mongoose ejs

javascript - 如何从console.table获取数据?

javascript 事件无法识别我的函数

node.js - 如何确定导致 Node.js 中出现 UnhandledPromiseRejectionWarning 的原因?

javascript - 如何将 json 响应中的二进制图像保存到 S3 存储桶

ajax - 从 get 请求获取数据?

javascript - 如何在 route 使用服务属性?