Asynchorous Programming Basics Question

Hello!

I have a problem on Asynchorous Programming section.

Link to this article:

In the “General Asynchorous Programming Concepts” section, this is said

The second problem is that although code run in a worker is not blocking, it is still basically synchronous. This becomes a problem when a function relies on the results of multiple previous processes to function. Consider the following thread diagrams:

Also this about “Promises” is said,

To fix such problems, browsers allow us to run certain operations asynchronously. Features like [Promises] allow you to set an operation running (e.g. the fetching of an image from the server), and then wait until the result has returned before running another operation:

What is the use of promises then? It seems like promises also makes the code synchorous just like the Web Workers for some tasks(e.g. the fetching of an image from the server). What is the special additional feature that promises give?

Thank you.

Hi @niwanthakaweragoda06!

workers and promises are fundamentally different things.

Running code in a worker happens in a different thread, so it doesn’t block the main thread and can improve performance, but it is still synchronous — the code will still fail if it depends on a previous value that has not arrived yet.

Promises request an operation to happen, but then wait on that result to return before running follow-on code.

You could combine the two, for example request some kind of value via a promise, but then don’t pass subsequent code to a worker until the promise fulfills.

Does that mean the difference between workers and promises is this?

  1. If the required operations for workers is not there in time, the code will give an error

2.If the required operations for a promise is not there in time, it will just wait until the requirements are fulfilled.

Sorry for my English btw.:grin::grin::grin:

Yes, that is basically right.

Consider that a worker is basically a separate thread in which some code is running, parallel to the main thread in which code normally runs. But a worker is more limited than the main thread, for example you can’t run code in a worker that manipulates the DOM.

A Promise on the other hand is a code feature that runs inside a thread. You are able to run a Promise inside a worker, or inside the main thread, afaik.