0
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)
         });
  });
}

In the above function getusername() I am passing userid 35

Data prints //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"
}]

I have to return corresponding email when userid equals data.id how it is possible?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Sush
  • 1,449
  • 8
  • 26
  • 51

1 Answers1

1

First, you can't return a value from the method as it is asynchronous, you need to use a callback pattern to solve this like

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
})

See How to return the response from an AJAX call?

Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • @Sush share how you have used the method `getusername` – Arun P Johny Feb 21 '14 at 10:53
  • one thing also am doing when userid="guest" i have to return callback(userid) and if userid="35" i have to return callback(data[0].emai;) – Sush Feb 21 '14 at 11:04
  • `function getusername(userid, callback) { $.get('/getRecentSignups', function (data) { if (data.id === userid) { callback(data[0].email); } else { callback(userid); } }); }`and that call back eoor is not getting now – Sush Feb 21 '14 at 11:06
  • @Sush but you removed the filter logic why is that – Arun P Johny Feb 21 '14 at 11:11
  • @Sush your initial logic and the one posted above does not match – Arun P Johny Feb 21 '14 at 11:13
  • i think while using that filter it doent returns data when userid="guest" dats y i remove that – Sush Feb 21 '14 at 11:13
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/48047/discussion-between-arun-p-johny-and-sush) – Arun P Johny Feb 21 '14 at 11:13