8

I'm beginning to teach myself javascript and am having trouble returning from a function inside a promise. My code, essentially, looks like this:

foobar = function(x,y){
    //code that doesn't matter
    return promiseFunction(
        function(results){
           console.log("promise completed")
           console.log(output)
           return output;}
        function(err){throw error;});

console.log(foobar('1','2'));

This prints

undefined
promise completed
what I want the result to be

I'm new to asynchronous programming and am not certain what I am doing wrong.

DazedAndConfused
  • 771
  • 3
  • 8
  • 19

2 Answers2

7

You don't return inside a promise. You chain another task after its completion - getting back a new promise for the completion of the chained task:

function foobar(x,y){
    // Assuming that promiseFunction does return a promise
    return promiseFunction().then(function(results){
         console.log("promise completed")
         console.log(output)
         return output;
    }, function(err) {
         throw error;
    });
}
foobar('1','2').then(function(output) {
    console.log(output);
})

If promiseFunction does not return a promise yet, check this section of the Q documentation about how to construct promises for a few examples and patterns.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • If I call foobar('1','2').then... I get "TypeError: Cannot call method 'then' of undefined". This presumably means foobar('1','2') does not return a promise? Looking around it looks like wrapping promiseFunction()... in a $.ajax() should fix that. How do I add jquery to just a javascript file? There is no HTML file. – DazedAndConfused Mar 06 '14 at 19:17
  • Well, the function I posted *does* `return` a promise. Does `promiseFunction` return the result of `$.ajax`? If you don't already use jQuery, you should better use a different library. How are you executing the script without HTML? There's probably some kind of `import` or `require` in such an environment. – Bergi Mar 06 '14 at 19:30
6

Asynchronous functions don't return (or at least, not reliably). By the time you get a value from your asynchronous function, console.log has already run with what it has (in this case, nothing, or undefined). This is a lesson I learned hard and fast when I started out with it. If you want something to happen after an asynchronous function, you have to call it inside of the asynchronous function.

See the thread How to return the response from an AJAX call? for more info and suggestions.

Community
  • 1
  • 1
Dissident Rage
  • 2,610
  • 1
  • 27
  • 33