我正在一个更大的应用程序中构建一个小 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)
并且日志按预期返回响应。那我错过了什么?
最佳答案
函数 getAxiosUrls
和 getNbShares
不返回 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/