Search code examples
javascriptecmascript-6es6-promise

Destructuring promise callback


There is a promise in my code:

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

I'd like to know is there any variants to destructure my 'result' variable on then call (something like .then({result.array(): errors} =>...) and not to make let errors = result.array(); assignment.


Solution

  • I believe it's impossible with the native promise. You can change this code a bit:

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

    Or you can use bluebird. It has a call method:

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

    But in the case you need to cast your promise to Bluebird promise