Is changing the meaning of promise methods a good

2019-09-20 06:13发布

问题:

I have a long running method in Node.js that keeps listening for command line output until the user closes the command or an error halts. Long story short, this method had, among others, three callbacks:

  • on_receive: Returns any new output from the command line to the callback, either as string or a converted json.
  • on_end: When the execution is terminated by the user, I send this.
  • on_error: When the command line prompts an error, I send it to the user. It always means the end of the command line execution, so on_end is called afterwards (though it could be called before if needed).

After any time the command is called, I keep the spawned child referenced, so I can kill it later or limit the amount.

Now, I was planning to move to promises (I'm using the library from Kris Kowal, q, but the three legs of the promise are not exactly how my callbacks are (taken from his wiki):

  • resolve: Calling resolve with a fulfilled promise causes promise to be fulfilled with the passed promise's fulfillment value.
  • reject: Calling reject with a reason causes promise to be rejected with that reason.
  • notify: Calling notify with a value causes promise to be notified of progress with that value. That is, any onProgress handlers registered with promise or promises derived from promise will be called with the progress value.

It would make sense to tie on_error to reject and maybe on_end to resolve (although this may also come from an error), but the most important command to track in this case, on_receive, is not actually related to a "progress", as the wiki states.

This code I'm doing is a node package for public use, so I don't know if using notify in this way would be actually confusing to other developers.

回答1:

Is changing the meaning of promise methods a good idea?

Definitely not.

the three legs of the promise are not exactly how my callbacks are

They don't need to be. Most promises don't even have a notion of progress, that's why it was deprecated in V2. The only thing you need to keep in mind: A promise represent a result that will asynchronously become available.

It would make sense to tie on_error to reject and maybe on_end to resolve (although this may also come from an error)

No, on_end should not be called from an error. A promise can only either signal the success of a process (fulfilled) or failure (rejected). A process can't do both.

the most important command to track in this case, on_receive, is not actually related to a "progress"

Yes. A progress is an output signal. The way you describe your on_receive callback, it is an input to your function that describes how to process some data. It may not be supplied lazily, but is essential to the functions operation. In that case, it should simply be (stay) a parameter.