1

So the following code is functional, just one function with variation of specs, but I am kind of suspicious, I believe it looks ugly specially with the callback, it really needs refactoring, any ideas on how it can be refactored to be maintainable and overcome flaws?

await rps_id.map((rp_id) => {
                return new Promise((resolve, reject) => {
                    Part.Model.updateOne({
                            _id: rp_id
                        }, {
                            invoiceId: invoice._id
                        }).then(function(result) {
                            return resolve();
                        })
                        .catch(() => {
                            reject();
                        });
                });
            });

this is the rest of the code: https://codepen.io/0xf10yd/pen/PopRWpz

I'd appreciate your help a lot, thanks in advance

1 Answer 1

1

You already make use of await, so I'd suggest changing all the code to use async/await to retain consistency.

The returned Promise inside the arrow function actually doesn't serve a purpose. You resolve inside a .then and reject inside a .catch. So unless there was some extra handling of the response or the thrown error, the returned promise is redundant.

Since Part.Model.updateOne already returns a promise (since you're using .then on it), I'm guessing you could probably trim it a lot like so:

await rps_id.map((rp_id) => Part.Model.updateOne({
            _id: rp_id
        }, {
            invoiced: invoice._id
        });

I'm not really able to test this, but it should work just like your code.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.