Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserve then() catch() format when using Prettier JS

I just started using the PrettierJS Plugin for VSCode and I am looking for a way to preserve my code format of my service calls (and subsequent Promises).

I know you can add the //prettier-ignore comments just before the code block to preserve the code pattern, but since i do this all over my app, i do not want to add that comment-line everywhere.

Right now, my code block looks like this:

       return this.thingService.addThing(newThing)
            .then(wonFunction)
            .catch(lostFunction);

But when i do the Prettier format command i get this:

    return this.accessData.addRight(newRight).then(wonAddAccessRight).catch(lostAddAccessRight);

I want a way to preserve my code blocks from changing without using the //prettier-ignore comments.

like image 275
MaylorTaylor Avatar asked Jul 18 '17 17:07

MaylorTaylor


People also ask

Does Prettier format JavaScript?

Prettier is an opinionated code formatter for JavaScript and other popular languages. Prettier enforces a consistent format by parsing code and reprinting it with its own rules that take the maximum line length into account, wrapping code when necessary.

How do I use Prettier auto format?

Command+Shift+P to open it. It will show search bar with right arrow >, just start typing Format Document With, and you will come up with results as below. Select Format Document With and again you will be asked for few options. Select Prettier — Code Formatter and your file will be formatted.

How do I fix Prettier in VS Code?

Open up VSCode settings in UI mode by selecting File > Preferences > Settings or press Ctrl + ,. Input “formatter” in the search box. Once you see Editor: Default Formatter section, select . This setting allows you to define a default formatter which takes precedence over all other formatter settings.


1 Answers

Prettier now automatically breaks a chain of 3 or more functions in separate lines (current version as I'm writing is 1.9.1), so the formatting is a bit different from what OP requested:

return this.accessData
  .addRight(newRight)
  .then(wonAddAccessRight)
  .catch(lostAddAccessRight);

But if you wanted to force it to break if you have only 2 functions, there's a hack that is to add a comment and Prettier will automatically break it:

return promise // force break
  .then(didResolve)
  .catch(didReject);
like image 164
Lucas Avatar answered Oct 18 '22 09:10

Lucas