我有一个调用数据库的函数。如果此操作成功,我想返回一个 bool 值,但我总是得到 undefined
。正如我所读,返回值也应该是一个 promise ,但如果我想 then/catch
“ promise ”,我的函数将返回一个 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;
});
};
我的函数调用如下所示:foobar({1: 'a'})
。如何以正确的方式获取 bool 返回值?
我已经尝试过以下两个选项:
首先我认为返回值是一个普通的 bool 值:
const return_value = foorbar({1: 'a'}); // returns undefined
在我了解到 then
函数中的返回值也是一个 promise 之后,我尝试 then/catch
它:
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
输出清楚地表明结果不是 promise,它只是 undefined
。感谢您的帮助。
最佳答案
您不会从 foobar
函数本身返回任何内容 - 只是调用 .then
和 .catch
。
return db.call(data).then(...).catch(...);
您还可以将 foobar
更改为 ES6 箭头函数并利用隐式返回:
const foobar = data => db.call(data).then(...).catch(...);
请注意,如果您使用 const
或 let
,ES6 函数在定义之前将无法访问 - 所以请确保您使用的是箭头函数,它们都在顶部的一个区域中定义。 ES5 函数没有这样的限制,因为它们都位于任何代码运行之前。
关于javascript - promise 中的返回值 then 始终未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56997580/