Reputation: 975
I have a function that makes a database call. I want to return a boolean value if this operation is successful, but I always get undefined
. As I've read the return value should be a promise as well, but if I want to then/catch
the "promise" my function returns an undefined
.
const foobar = function(data) {
db.call(data).then(function(res) {
console.log(res); // returns the expected data, e.g.["foobar", "foo", "bar"]
return res.includes("bar");
}).catch(function(err) {
// if an error occures, the function should ...
// ... return a false value as well
return false;
});
};
My function call looks like this: foobar({1: 'a'})
. How can I fetch the boolean return value in the correct way?
I've tried it with the following two options:
First I thought that the return value would be a normal boolean value:
const return_value = foorbar({1: 'a'}); // returns undefined
After I've read that the return value within a then
function would be a promise as well, I've tried to then/catch
it:
const return_value = foobar({1: 'a'}
).then(function(res) {
console.log(res);
}).catch(function(err) {
console.log(err);
});
Uncaught TypeError: Cannot read property 'then' of undefined
The output clearly indicates that the result is not a promise, it's just undefined
. I appreciate any help.
Upvotes: 1
Views: 131
Reputation: 44087
You're not returning anything from the foobar
function itself - just the calls to .then
and .catch
.
return db.call(data).then(...).catch(...);
You could also change foobar
to an ES6 arrow function and take advantage of the implicit return:
const foobar = data => db.call(data).then(...).catch(...);
Note that ES6 functions won't be accessible before they're defined if you use const
or let
- so make sure if you're using arrow functions, they're all defined in one area at the top. ES5 functions have no such restriction because they are all located before any of the code runs.
Upvotes: 4