2017-01-23 98 views
-1

我想從另一個函數調用一個函數(refresh_access_token)並從中創建一個Promise鏈。但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不返回任何東西。您的唯一回報聲明位於needle.post回調中。您應該首先返回:

return MercadoLibre.findOne(...); 

但是,您正在混合承諾和回調(用於needle.port調用)。我會建議查看承諾與回調以及如何一起使用它們。這裏有一個關於如何將callback-apis轉換爲promises的好主意:How do I convert an existing callback API to promises?

另一種方法是使用needle與支持的承諾節點庫替換: