0

I need to make many API calls with different settings, so I'm trying to write a function that will take a settings object and return text. I had this working before function-izing it, but now I can't figure out how to get the data out. The data variable is good here, but how can I pass it back to answer? I tried adding a this reference, this is my current attempt.

 function REST(settings) {
    var whatIneed;
    var parent = this;
    client.request(settings).then(
        function(data) {
            console.log(data);
            parent.whatIneed = data;
        },
        function(response) { PromiseError(response); } )
    console.log(whatIneed);
    return whatIneed;
}

answer = REST(settings);
Elliott B
  • 980
  • 9
  • 32

1 Answers1

0

Your problem is that you are using an asynchronous call that returns a promise in a synchronous manner. When you return whatIneed at the end of REST its value will still be undefined because the then block from the client call has not executed yet.

If you are using a transpiler you could use await to await the data before returning it or you could return the promise directly from REST and then use it like REST(settings).then(function(data) { // do something})

k-nut
  • 3,447
  • 2
  • 18
  • 28
  • I've just read the linked super-thread on the topic and now I understand the problem. I did have it working before by returning the promise directly like you said, but I was trying to avoid having lots of nested callbacks. I will look into `await`, thanks. – Elliott B Jul 26 '18 at 20:36