Javascript中带有返回值的嵌套函数

Nested functions in Javascript with a return value

本文关键字:嵌套 函数 返回值 Javascript      更新时间:2023-09-26

我想说,我是一个过渡到中级程序员的初学者,我不完全理解闭包以及带有返回值的嵌套函数。我读了一些书,真的无法理解。

以下代码将只返回未定义的。我想这是因为它是一个嵌套函数,但我不确定我是否理解如何修复它

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