简体   繁体   中英

Javascript: How to determine whether to promisefy a function?

Consider small helper functions, some of which are obvious candidates for async / promise (as I think I understand them):

exports.function processFile(file){
  return new Promise(resolve => {
    // super long processing of file
    resolve(file);
  });
}

While this:

exports.function addOne(number){
  return new Promise(resolve => {
    resolve(number + 1);
  });
}

Seems overkill.

What is the rule by which one determines whether they should promise-fy their functions?

I generally use a promise if I need to execute multiple async functions in a certain order. For example, if I need to make three requests and wait for them all to come back before I can combine the data and process them, that's a GREAT use case for promises. In your case, let's say you have a file, and you need to wait until the file and metadata from a service are both loaded, you could put them in a promise.

If you're looking to optimize operations on long running processes, I'd look more into web workers than using promises. They operate outside the UI thread and use messages to pass their progress back into the UI thread. It's event based, but no need for a promise. The only caveat there is that you can't perform actions on the DOM inside a web worker.

More on web workers here: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers

What is the rule by which one determines whether they should promise-fy their functions?

It's quite simple actually:

  • When the function does something asynchronous, it should return a promise for the result
  • When the function does only synchronous things, it should not return a promise

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM