Is variable scope combined with promises good practice?

I often see code like this:

(the code is completely composed from scratch)

something.someFunction('foobar')
    .then(function(user) {
        var email = user.email();
        return user.getSomething();
    })
    .then(function(something) {
        var metadata = something.metadata();
        return user.getRelation(metadata);
    })
    .then(function(relation) {
        return email.send(relation, metadata);
    })
    .catch(function(err) {
        console.log(err);
    })
;

      

Is this common practice? Personally, I find it not very clean and not readable. What are the alternatives? All I could think of was something like putting all the necessary things into an object and passing that instead. However, this can be very large with long promises:

something.someFunction('foobar')
    .then(function(user) {
        return {
            email: user.email(),
            something: user.getSomething(),
        };
    })
    .then(function(state) {
        return {
            email: state.email,
            metadata: something.metadata(),
            relation: user.getRelation(metadata),
            // 'something' is not needed anymore ...
        };
    })
    .then(function(state) {
        return {
            result: email.send(state.relation, state.metadata),
            // and everything else that might be needed later on ...
        };
    })
    .catch(function(err) {
        console.log(err);
    })
;

      

Will it still work as expected? If not, what is the way to create something like this? Again, I just came up with this code from scratch as a pure illustrative example.

+3
javascript promise


source to share


No one has answered this question yet

See similar questions:

598
How do I access the results of previous promises in the .then () chain?

or similar:

4086
What's the difference between using "let" and "var"?
2660
Closing JavaScript Inner Loops - A Simple Practical Example
2038
Is there a standard function for testing null, undefined, or empty variables in JavaScript?
1957
How do I determine if a variable is "undefined" or "null"?
1850
What is the scope of variables in JavaScript?
1643
How do you check if a variable is an array in JavaScript?
1513
Check if a variable is a string in JavaScript.
1246
What is the difference between promises and observables?
806
Working with $ scope. $ Emit and $ scope. $ On
2
ECMAScript 6 Chained Promises



All Articles
Loading...
X
Show
Funny
Dev
Pics