How to return the proper data from this function?
function getUserData(name) {
var userData = {};
twitter.get('http://api.twitter.com/1/users/lookup.json', {screen_name:name}, function(data) {
userData = {
name: data[0].screen_name,
screenname: data[0].screen_name,
id: data[0].id,
url: data[0].url,
description: data[0].description
}
});
return userData;
}
I want to be able to writ开发者_JAVA技巧e something like:
var userData = getUserData(name);
and have it return that userData object.
You don't.
AJAX calls are asynchronous. You need to use callbacks in some manner or another.
function getUserData(name, cb) {
var userData = {};
twitter.get('http://api.twitter.com/1/users/lookup.json', {
screen_name: name
}, function(data) {
userData = {
name: data[0].screen_name,
screenname: data[0].screen_name,
id: data[0].id,
url: data[0].url,
description: data[0].description
}
cb(userData);
});
}
getUserData(name, function(userData) {
// do stuff.
});
If your using jQuery 1.5 you can use deferred promises which are jQuery Deferred objects.
function getUserData(name, cb) {
var def = new jQuery.Deferred();
twitter.get('http://api.twitter.com/1/users/lookup.json', {
screen_name: name
}, function(data) {
var userData = {
name: data[0].screen_name,
screenname: data[0].screen_name,
id: data[0].id,
url: data[0].url,
description: data[0].description
}
def.resolve(userData);
});
return def.promise();
}
var promise = getUserData(name);
promise.done(function(data) {
// do stuff.
});
精彩评论