2017-01-23 10 views
-1

私は別の関数から関数(refresh_access_token)を呼び出して、そこからプロミスチェーンを作成しようとしています。しかし、refresh_access_token内の戻り関数は機能しません。 refresh_access_tokenは、完了したときに呼び出し元に戻りません。 私はこのメッセージを受信して​​います:関数が約束を返していない

Unhandled rejection TypeError: Cannot read property 'then' of undefined 

どのように私はこの問題を解決することができますか?

これらは、2機能コードです:

exports.refresh_access_token = function(environment_hash) { 

    var MercadoLibre = require('../../models/index').MercadoLibre; 
    var needle = require('needle'); 
    const load = require('express-load'); 
    var meli = require('mercadolibre'); 
    var request=require('request'); 
    const mysql = require('mysql'); 
    const dotenv = require('dotenv').config({path: '../../.env'}); 

    var oauth_url = 'https://api.mercadolibre.com/oauth/token'; 


    var env_hash = environment_hash; 

    where = { environment_hash: env_hash }; 

    MercadoLibre.findOne({where: where}).then(function (account) { 
     if (!account) { 
      // Item not found 

     } else { 
      // Found an item, update it 
      needle.post(oauth_url, { 
       grant_type: 'refresh_token', 
       client_id: process.env.MERCADOLIBRE_CLIENT_ID, 
       client_secret: process.env.MERCADOLIBRE_SECRET, 
       refresh_token: account.refresh_token 
      }, { 
      }, function (err, res, body) { 
       if (body) { 
         expires_in = new Date(); 
         expires_in.setUTCHours(0); 
         expires_in.setTime(expires_in.getTime() + 21600*1000); 

         values = { 
          refresh_token: body.refresh_token, 
          expires_in: expires_in 

         }; 

         where = { environment_hash: env_hash }; 

         return MercadoLibre.update(values, {where: where}); 


       } 
      });  
     } 
    }); 

} 


exports.run_mercadolibre_jobs = function() { 

    var MercadoLibre = require('../../models/index').MercadoLibre; 


    var values = { 
       attributes: ['environment_hash'], 
       raw: true 
     }; 

     MercadoLibre 
      .findAll(values) 
      .then(function(accounts) { 

       Promise.all(accounts.map(function(account) { 

        module.exports.refresh_access_token(account.environment_hash) 
        .then(function(response) { 

         console.log(response); 

        }) 
        .catch(function(response){ 
         console.log(response); 

        }); 

       }));   
      }); 
} 
+0

"未処理の拒否"?それは実際にそれを言うのですか? – Carcigenicate

+0

これは基本的にNPEです。あなたは未定義の値を持っています。なぜデバッグするかを調べる。 – Carcigenicate

答えて

1

あなたの機能refresh_access_tokenは何も返していません。あなたの唯一のreturn文は、needle.postコールバックの中にあります。

return MercadoLibre.findOne(...); 

しかし、約束事とコールバック(あなたのneedle.portコールで使用されている)を混在させています。プロミスとコールバックのレビューと、それらを一緒に使用する方法をお勧めします。 callback-apisを約束に変換する方法についての良いスレッドは、How do I convert an existing callback API to promises?です。

別の方法としては、約束サポートノードライブラリとneedleを使用して交換することになります。

関連する問題