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 pleted")
console.log(output)
return output;}
function(err){throw error;});
console.log(foobar('1','2'));
This prints
undefined
promise pleted
what I want the result to be
I'm new to asynchronous programming and am not certain what I am doing wrong.
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 pleted")
console.log(output)
return output;}
function(err){throw error;});
console.log(foobar('1','2'));
This prints
undefined
promise pleted
what I want the result to be
I'm new to asynchronous programming and am not certain what I am doing wrong.
Share Improve this question asked Mar 6, 2014 at 17:55 DazedAndConfusedDazedAndConfused 8293 gold badges10 silver badges19 bronze badges2 Answers
Reset to default 7You don't return
inside a promise. You chain another task after its pletion - getting back a new promise for the pletion of the chained task:
function foobar(x,y){
// Assuming that promiseFunction does return a promise
return promiseFunction().then(function(results){
console.log("promise pleted")
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.
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.