2016-09-23 11 views
1

私は大きなアプリケーションの中に小さなノードのjsデータの廃棄機能を構築しています。私は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) 

をやったし、期待通りにログが私に応答を返すことを確認します。それで私は何を欠場したのですか?

+1

'getAxiosUrls'と' getNbShares'は何も返さない:https://stackoverflow.com/documentation/javascript/231/promises – Andreas

+1

'return'の問題のほかに、あなたは以前の'const getNbShares = function(urls){...'のような結果です。 – Redu

答えて

3

機能getAxiosUrlsgetNbSharesは約束を返しません。これは、サイドノートとして

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

次のようになります。これは、この関数で返された約束は場合にundefinedに解決するようになりますので、私は、getNbShares機能で.catchの除去をお勧めします(あなたはcatchハンドラで何も返されません)。エラーから回復するために何かできることがない限り、プロミスチェーンの最後にエラー処理を追加する方がよい場合があります。

+0

もし私の関数が何かを返すが、約束を返すのではないと分かっていれば。しかし、私は約束について多くのことを読んだことがありますが、それはまだ分かりません。もし何か価値があると約束すれば、私の関数は戻り値を返す前に実際に値を返していました。 –

+1

あなたの関数は何も返していませんでした。 'getAxiosUrls'関数をもう一度見てください。return文がないので、' undefined'が返されます。なぜなら 'Can not read 'プロパティと' undefined'エラーを得る理由です。 getAxiosUrlsの戻り値 – forrert

+0

getAxiosUrls()setTimeout(function(){console.log(urls)}、5000)を実行したときに、私が望む結果を得ていたという事実は、私が返すものがあることを意味します。 –

関連する問題