0

I'm a total beginner at Javascript, and I'm trying to get some data from an API, and have code that looks roughly like this:

function getData(uid) {
    app.login({ email: userEmail, password: userPassword}).then(function(response){
        var user = response.user;
        var result = user.read(uid).then(function(){
            return "foobar";
        });
        return result;
    });
}

function doStuff(uid) {
    var result = getData(uid);
    // do stuff on result
    console.log(result); //returns promise
}

So I want to access the result var result = getData(user, uid); which only returns a Promise object. What's the best way to get access to the "foobar" result?

veor
  • 175
  • 1
  • 2
  • 6

1 Answers1

1

You can't return a result from a deferred request. What you should do is use a callback function like this...

function getData(uid, callback) {
    app.login({ email: userEmail, password: userPassword}).then(function(response){
        var user = response.user;
        var result = user.read(uid).then(function(){
            return "foobar";
        });
        callback(result);
    });
}

function doStuff(uid) {
    getData(uid, function(result) {
        // do stuff on result
        console.log(result); //returns promise
    });
}
Reinstate Monica Cellio
  • 25,975
  • 6
  • 51
  • 67