Javascript中的嵌套函数,返回值

时间:2016-05-15 16:49:45

标签: javascript node.js twitter

我会说我是初学者过渡到中级程序员而我并不完全理解闭包以及带有返回值的嵌套函数。我做了一些阅读,并不能真正地围绕它。

以下代码仅返回undefined。我将假设这是因为它是一个嵌套函数,但我不确定我是否理解如何修复它。

var Twit = require('twit');
var request = require('request');

var T = new Twit({
  consumer_key:         'Removed for security reasons',
  consumer_secret:      'Removed for security reasons',
  access_token:         'Removed for security reasons',
  access_token_secret:  'Removed for security reasons',
});

var stream = T.stream('statuses/filter', {track: '#instagram'});

stream.on('tweet', function(tweet){
  if(!tweet.entities.media){
    console.log("No photo here");
  }else{
    var imageUrl = JSON.stringify(tweet.entities.media[0].media_url).replace(/^"(.*)"$/, '$1');
    console.log(describeImage(imageUrl) + " - " + imageUrl);
  }
});


function describeImage(imageUrl){
  
var options = {
    url: "https://api.projectoxford.ai/vision/v1.0/describe?maxCandidates=1",
    json: {url: imageUrl},
    method: 'POST',
    headers: {
      'Content-type' : 'application/json',
      'Ocp-Apim-Subscription-Key' : 'Removed for security reasons'
    }
}

  request(options, function(err, res, body){
    if(err){
      console.log(err);
    }
    //This is where I'm going wrong.
    return JSON.stringify(body.description.captions[0].text);
  });
  
  
}

任何帮助都会很精彩!

1 个答案:

答案 0 :(得分:0)

在代码1)中做了两处更改,其中进行了describeImage调用,2)你出错了



var Twit = require('twit');
var request = require('request');

var T = new Twit({
  consumer_key:         'Removed for security reasons',
  consumer_secret:      'Removed for security reasons',
  access_token:         'Removed for security reasons',
  access_token_secret:  'Removed for security reasons',
});

var stream = T.stream('statuses/filter', {track: '#instagram'});

stream.on('tweet', function(tweet){
  if(!tweet.entities.media){
    console.log("No photo here");
  }else{
    var imageUrl = JSON.stringify(tweet.entities.media[0].media_url).replace(/^"(.*)"$/, '$1');
    describeImage(imageUrl,function(imgUrl){
       console.log(imgUrl + " - " + imageUrl);
    });
  }
});


function describeImage(imageUrl,callBack){
  
var options = {
    url: "https://api.projectoxford.ai/vision/v1.0/describe?maxCandidates=1",
    json: {url: imageUrl},
    method: 'POST',
    headers: {
      'Content-type' : 'application/json',
      'Ocp-Apim-Subscription-Key' : 'Removed for security reasons'
    }
}

  request(options, function(err, res, body){
    if(err){
      console.log(err);
    }
    //Call Callback function here
    return callBack(JSON.stringify(body.description.captions[0].text));
  });
  
  
}