function getusername(userid) {
$.get('/getRecentSignups', function (data) {
console.log(JSON.stringify(data);
//prints
{"_id":"5306e7fd80b1027ad2653db4","email":"priya@gmial.com","id":"27","password":"priya","signedtime":"2014-02-21 11:15:33"},{"_id":"5306e81880b1027ad2653db5","email":"anju@gmail.com","id":"35","password":"anju","signedtime":"2014-02-21 11:16:00"}]
// userid passing here is 35
data = data.filter(function(val) {
return (val.id === userid)
});
});
}
在上面的函数getusername()
中,我正在传递userid 35
数据打印//打印
{
"_id": "5306e7fd80b1027ad2653db4",
"email": "priya@gmial.com",
"id": "27",
"password": "priya",
"signedtime": "2014-02-21 11:15:33"
},
{
"_id": "5306e81880b1027ad2653db5",
"email": "anju@gmail.com",
"id": "35",
"password": "anju",
"signedtime": "2014-02-21 11:16:00"
}]
当userid
等于data.id
时,我必须返回相应的电子邮件吗?
答案 0 :(得分:1)
首先,你不能从方法中返回一个值,因为它是异步的,你需要使用一个回调模式来解决这个问题,如
function getusername(userid, callback) {
$.get('/getRecentSignups', function (data) {
data = data.filter(function (val) {
return (val.id == userid)
});
if (data && data.length) {
callback(data[0].email);
} else {
callback(userid);
}
});
}
getusername(35, function (email) {
//do something
})