链接function如诺言

我在一个更大的应用程序内部构build了一个小节点js数据报废function。 我不太喜欢Javascript的承诺,请原谅我的误解。 不知道我的标题真的构成了我的问题。

所以我有这个:

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) 

我试过一些东西,但大多数时候我有以下错误: Cannot read property 'then' of undefined 。 还要确保我的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)); } 

注意:我build议删除getNbShares函数中的getNbShares ,因为如果发生错误(在catch处理程序中没有返回任何内容),这将导致此函数返回的promise被parsing为undefined 。 在承诺链的最后添加error handling通常会更好,除非您可以从错误中恢复。