【问题标题】:Destructuring promise callback解构承诺回调
【发布时间】:2017-08-15 10:35:30
【问题描述】:

我的代码中有一个承诺:

req.getValidationResult()
        .then(result => {
            let errors = result.array();
            if (errors.length) {
                return res.status(400).json({ errors: errors });
            }
            
            return next();
        });

我想知道是否有任何变体可以在调用时解构我的“结果”变量(类似于.then({result.array(): errors} =>...)而不是进行let errors = result.array(); 赋值。

【问题讨论】:

    标签: javascript ecmascript-6 es6-promise


    【解决方案1】:

    我相信原生承诺是不可能的。您可以稍微更改此代码:

    req.getValidationResult()
            .then(({array}) => array())
            .then(errors => {
                if (errors.length) {
                    return res.status(400).json({ errors: errors });
                }
                return next();
            });
    

    或者你可以使用蓝鸟。它有一个call 方法:

    req.getValidationResult()
            .call('array')
            .then(errors => {
                if (errors.length) {
                    return res.status(400).json({ errors: errors });
                }
                return next();
            });
    

    但在这种情况下,您需要将您的承诺转换为 Bluebird 承诺

    【讨论】:

      猜你喜欢
      • 2016-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-23
      • 1970-01-01
      • 1970-01-01
      • 2016-09-28
      • 1970-01-01
      相关资源
      最近更新 更多