Giter VIP home page Giter VIP logo

Comments (5)

xjamundx avatar xjamundx commented on May 18, 2024 3

@EvgenyOrekhov great question thanks!

These rules definitely don't represent the best or the only way to make promises, but in my experience when I've found myself nesting inside of then() usually it's a big warning sign that things are about to get more confusing than I want them to get!

If you can use async/await you'd probably want to do this

let object = await database.read({id: 123})
await database.update(object)
await transport.respond(object)

If you cannot async/await your code and you cannot modify database.update directly you can do this instead:

function updateDB(data) {
    return db.update(data).then(function(success) {
        if (!success) throw new Error('Could not write to DB properly')
        return data
    })
}

Then you can write some super tight promise like this:

return database.read({id: 123})
    .then(mutateObject)
    .then(updateDB)
    .then(transport.respond)
    .catch(transport.error);

There are 100 ways to write promises and in general if you have a success/fail situation instead of returning a boolean you might want to throw and take advantage of that built-in error handling mechanism and then use the normal return for something you want in the success value.

This might not work for you, so in that cases you don't need the rule.

from eslint-plugin-promise.

devhopes-ca avatar devhopes-ca commented on May 18, 2024 3

Can someone please help me to fix the no-nesting promises warning with this method?

Here is the code:

getPayoutsPending(uid).then((array) => {
    getPayoutsAmount(array).then((value) => { **// warning  Avoid nesting promises  promise/no-**nesting
    
        var valueTrunc = parseFloat(Math.round(value * 100) / 100).toFixed(2);

        const sender_batch_id = Math.random().toString(36).substring(9);
        const sync_mode = 'false';
        const payReq = JSON.stringify({
            sender_batch_header: {
                sender_batch_id: sender_batch_id,
                email_subject: "You have a payment"
            },
            items: [
                {
                    recipient_type: "EMAIL", 
                    amount: {
                        value: valueTrunc,
                        currency: "CAD"
                    },
                    receiver: "[email protected]",
                    note: "Thank you.",
                    sender_item_id: "Payment"
                }
            ]
        });

        paypal.payout.create(payReq, sync_mode, (error, payout) => {
            if (error) {
                console.warn(error.response);
                response.status('500').end();
                throw error;
            } else {
                console.info("payout created");
                console.info(payout);

                updatePaymentsPending(uid, sender_batch_id).then(() => { **// avoid nesting problems** 
                    response.status('200').end();
                    return;
                }).catch((error) => {
                    return console.error(error);
                })
            }
        });
        return null;
    }).catch((error) => {
        return console.error(error);
    })
    return null;
}).catch((error) => {
    return console.error(error);
})

There are two lines ... marked // avoid nesting problems that are causing the warnings.

Please help as what I have done doesn't seem to work.
Much appreciated

from eslint-plugin-promise.

alexander-akait avatar alexander-akait commented on May 18, 2024

Be good add option onlyCatch (maybe best name) for check only nesting catch in no-nesting rule.

from eslint-plugin-promise.

EvgenyOrekhov avatar EvgenyOrekhov commented on May 18, 2024

I constrained myself to the "JSLint" subset of JavaScript which doesn't allow async/await, so I'll stick to using function declarations. Thanks for the clarification!

from eslint-plugin-promise.

EvgenyOrekhov avatar EvgenyOrekhov commented on May 18, 2024

If you use a promise library (like Bluebird or Q) it likely has the .tap() method which you can use to avoid nesting when you need to return the original argument:

return database
    .read({id: 123})
    .tap(function (object) {
        /* ... code that changes the object ... */
        return database.update(object);
    })
    .then(transport.respond) // transport.respond will receive the object
    .catch(transport.error);

from eslint-plugin-promise.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.