[removed] How to determine whether to promisefy a function?

前端 未结 2 1701
旧时难觅i
旧时难觅i 2020-12-21 20:40

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

exports.function processFile(file){         


        
相关标签:
2条回答
  • 2020-12-21 21:11

    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
    0 讨论(0)
  • 2020-12-21 21:23

    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

    0 讨论(0)
提交回复
热议问题