我正在创建一个 Twitter 机器人,它从同一 API Wordnik 发出请求,但每个请求都取决于上一个请求的结果。因此,我决定尝试使用回调创建一些代码,以确保在下一个函数运行之前从 API 返回所有信息。我在设置它时遇到了麻烦,我看过很多例子,但我就是无法掌握它的窍门。 (抱歉代码困惑)。
我现在遇到的错误是 thenRunThisFunction(getRhyme) 上的函数 getWord() 中的“未定义不是函数”。我想知道我的回调是否有一个小错误,或者我解决这个问题的整个方法是否不正确?
function runBot() {
var request = require('request');
var Twit = require('twit');
var async = require('async');
var T = new Twit({
consumer_key: '' // Your Consumer Key
, consumer_secret: '' // Your Consumer Secret
, access_token: '' // Your Access Token
, access_token_secret: '' // Your Access Token Secret
});
var WORDNIKAPIKEY = '';
// GLOBAL VARS
var randomWord; //get random word
var rhymingWord; //get rhyming word
var bogusDef; //get def of rhyming word
var tweet; // combined random and bogusdef
function getWord(thenRunThisFunction){
request('http://api.wordnik.com:80/v4/words.json/randomWord?hasDictionaryDef=false&minCorpusCount=0&maxCorpusCount=-1&minDictionaryCount=1&maxDictionaryCount=-1&minLength=5&maxLength=-1&api_key=' + WORDNIKAPIKEY, function (error, response, body1) {
if (!error && response.statusCode == 200) {
//console.log(body1) // Show the HTML for the Google homepage.
var pparsedData = JSON.parse(body1);
console.log("Word: " + pparsedData.word);
// set random word
randomWord = pparsedData.word;
thenRunThisFunction(getRhyme);
}
})
}
// Get the rhyming word
function getRhyme(thenRunThisFunction){
request('http://api.wordnik.com:80/v4/word.json/' + randomWord + '/relatedWords?useCanonical=false&relationshipTypes=rhyme&limitPerRelationshipType=10&api_key=' + WORDNIKAPIKEY, function (error, response, body2) {
if (!error && response.statusCode == 200) {
//console.log(body2) // Show the HTML for the Google homepage.
var o = JSON.parse(body2);
console.log("Rhyme: " + o[0].words[0]);
// set rhyming word
rhymingWord = o[0].words[0];
thenRunThisFunction(getDef);
}
})
}
// GET THE SEXY DEFINITION BABY, BEACH BOD
function getDef(thenRunThisFunction){
request('http://api.wordnik.com:80/v4/word.json/' + rhymingWord + '/definitions?limit=200&includeRelated=true&sourceDictionaries=all&useCanonical=false&includeTags=false&api_key=' + WORDNIKAPIKEY, function (error, response, body3) {
if (!error && response.statusCode == 200) {
//console.log(body3) // Show the HTML for the Google homepage.
var newnew = JSON.parse(body3);
console.log("Definition: " + newnew[0].text);
// set definition
bogusDef = newnew[0].text;
randomWord = randomWord.charAt(0).toUpperCase();
tweet = randomWord + ": " + bogusDef;
thenRunThisFunction(postStatus);
}
})
}
function postStatus(){
T.post('statuses/update', { status: tweet }, function(err, data, response) {
if(err) {
console.log("There was a problem tweeting the message.", err);
}
});
console.log("status posted");
}
getWord();
}
runBot();
最佳答案
您没有将函数引用传递给 getWord()。
关于javascript - "undefined is not a function"使用回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30634503/