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.
The Promise.resolve() method "resolves" a given value to a Promise . If the value is a promise, that promise is returned; if the value is a thenable, Promise.resolve() will call the then() method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value.
Promises don't "return" values, they pass them to a callback (which you supply with . then()). It's probably trying to say that you're supposed to do resolve(someObject); inside the promise implementation. Then in your then code you can reference someObject to do what you want.
Returns a new Promise object that is resolved with the given value. If the value is a thenable (i.e. has a then method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise, the returned promise will be fulfilled with the value.
Promise.prototype.then() The then() method returns a Promise . It takes up to two arguments: callback functions for the fulfilled and rejected cases of the Promise .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With