【问题标题】:Return value within promise then is always undefined承诺中的返回值总是未定义的
【发布时间】:2019-11-21 16:01:06
【问题描述】:

我有一个调用数据库的函数。如果此操作成功,我想返回一个布尔值,但我总是得到undefined。正如我所读到的,返回值也应该是一个承诺,但如果我想then/catch“承诺”,我的函数会返回一个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'})。如何以正确的方式获取布尔返回值? 我已经尝试了以下两个选项:

首先我认为返回值是一个普通的布尔值:

const return_value = foorbar({1: 'a'}); // returns undefined

在我读到then 函数中的返回值也是一个承诺之后,我尝试then/catch 它:

const return_value = foobar({1: 'a'}
).then(function(res) {
    console.log(res); 
}).catch(function(err) {
    console.log(err); 
});

未捕获的类型错误:无法读取未定义的属性“then”

输出清楚地表明结果不是一个承诺,它只是undefined。感谢您的帮助。

【问题讨论】:

    标签: javascript ecmascript-6 promise return


    【解决方案1】:

    您不会从 foobar 函数本身返回任何内容 - 只是对 .then 和 .catch 的调用。

    return db.call(data).then(...).catch(...);
    

    您还可以将foobar 更改为 ES6 箭头函数并利用隐式返回:

    const foobar = data => db.call(data).then(...).catch(...);
    

    请注意,如果您使用 const 或 let,ES6 函数在定义之前将无法访问 - 所以请确保如果您使用箭头函数,它们都定义在顶部的一个区域中. ES5 函数没有这样的限制,因为它们都位于任何代码运行之前。

    【讨论】:

    • 谢谢,我明显是瞎子。有没有其他方法可以接收这样的返回值?还是有更好的方法?
    • 除非你使用 ES6 箭头函数的隐式返回特性,否则你需要这样做。我会用这种方法更新我的答案。
    猜你喜欢
    • 2015-09-27
    • 1970-01-01
    • 1970-01-01
    • 2019-07-30
    • 1970-01-01
    • 1970-01-01
    • 2016-05-27
    相关资源
    最近更新 更多