我正在使用Twitter API客户端Twit。我想知道如何在get请求后执行函数?
目前,getUsers()函数在printUsers()函数之后执行,但我执行了getUsers()函数,然后执行printUsers()函数。
console.log("Hello Bot");
var Twit = require('twit');
var config = require('./config');
var T = new Twit(config);
var randomUsers = [];
function getUsers() {
// search twitter for all tweets containing the word 'javascript'
var params = {
user_id: '3180043436',
count: 2
}
T.get('friends/ids', params, gotFriends);
T.get('followers/ids', params, gotFollowers);
function gotFriends(err, data, response) {
console.log(data.ids);
Array.prototype.push.apply(randomUsers, data.ids);
};
function gotFollowers(err, data, response) {
console.log(data.ids);
Array.prototype.push.apply(randomUsers, data.ids);
};
console.log();
}
function printUsers(){
console.log(randomUsers);
}
getUsers();
printUsers();
答案 0 :(得分:1)
您应该使用回调功能
$(function(){
$.ajax(
{
type: "GET",
dataType: "jsonp",
url: "http://example.com/json.php?callback=callNow",
} );
});
function callNow(data){
alert(data.name + " " + data.lastname);
}
注意url中的callNow,它也是函数名称
答案 1 :(得分:1)
Twit有希望支持。因此,如果你没有传递回调它将返回一个承诺。您可以收集这些承诺,并使用Promise.all或jQuery.when或async.parallel库方法并行运行所有这些承诺,最后在预付费数据上运行回调函数:
console.log("Hello Bot");
var Twit = require('twit');
var $ = require('jquery');
var config = require('./config');
var T = new Twit(config);
var randomUsers = [];
function getUsers(callback) {
// search twitter for all tweets containing the word 'javascript'
var params = {
user_id: '3180043436',
count: 2
};
var promise1 = T.get('friends/ids', params);
var promise2 = T.get('followers/ids', params);
$.when(promise1, promise2).done(function(data1, data2) {
randomUsers.push(data1.data.ids).push(data2.data.ids);
callback(randomUsers);
});
}
function printUsers(randomUsers){
console.log(randomUsers);
}
getUsers(printUsers);