0
我會說我是一個初學者轉換到中級程序員,我不完全理解閉包以及帶返回值的嵌套函數。我已經做了一些閱讀,不能真正包裹我的頭。JavaScript中的嵌套函數返回值
下面的代碼將只返回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);
});
}
任何幫助將是美好的!
'request'是異步的製作'describeImage'異步但您嘗試同步使用它。看看承諾(藍鳥)或回調。 – Wainage