[removed] How to determine whether to promisefy a

2020-02-15 05:04发布

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?

2条回答
\"骚年 ilove
2楼-- · 2020-02-15 05:17

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
查看更多
唯我独甜
3楼-- · 2020-02-15 05:18

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

查看更多
登录 后发表回答