0

So I just have read that Promises actually block code execution (here: Why is my chained promise blocking?), but I know that I can for sure run a promise with a call to a server api and it won't block the website code from running even if it takes many seconds. So how come Promise can sometimes block the execution and sometimes not.

Right now I'm writing an Electron app for personal use, I do a lot of I/O operations at one point so I used wrapped that code in a Promise, as I thought it will make that code run in parallel to the rest of my app, but as it turns out it doesn't and whenever that Promise is called the whole app stops working until the Promise resolves.

ncpa0cpl
  • 192
  • 1
  • 13
  • 3
    Promises don't block anything, they are event-based. The synchronous code within them does. If you run a very long loop inside a function which returns a Promise, it's still on the same thread, it's not run in parallel. If you want to run synchronous code in parallel, you should look into web workers – blex Jan 31 '21 at 21:57
  • 4
    "*So how come Promise can sometimes block the execution and sometimes not.*" as the answer you link to says, promises are a notification system. They don't "run" anything - a promise is a value that is currently pending. Whether the operation is blocking or not depends on what that operation is. If you run a long loop, it's going to block. If you do a network call, the execution doesn't wait for the call to finish, so it doesn't block. – VLAZ Jan 31 '21 at 21:58
  • 1
    You misread the answer to that linked question. It never said that promises block code execution. See step 3: "*Your long-running synchronous code is called from that executor callback*" - this is the blocking operation. The promise has nothing to do with that. "*I know that I can for sure run a promise with a call to a server api*" - nope. You cannot "run" a promise. You can make a non-blocking (asynchronous) request to a server, using a builtin asynchronous api (like XHR or fetch), and you can even construct a promise for the result, but it's not the promise that makes anything asynchronous. – Bergi Jan 31 '21 at 22:30
  • 1
    "*I do a lot of I/O operations*" - how? Could you use asynchronous I/O there? – Bergi Jan 31 '21 at 22:31

0 Answers0