user3115001 user3115001 - 3 months ago 8
Javascript Question

How to think when working with promises

I'm working for the first time with async programming, specifically with promises in Javascript and I'm really confused with it. I'm still thinking like we do in C, PHP, C# and so on where for each step the next one can be sure of it's completion. This is easy to work, because if we have a code like that (in C# for example)

IEnumerable<Page> pages = pagesRepository.getAll();


we can be sure in the next line that all pages are available for us to use in the
pages
object. This makes life easier, because we can already do work with that data properly.

Now, in JS with promises we would have something like

var pages = dataService.getPages();


and this would not return the data, but just a promise which is very different. Of course we can add a callback with
then
but I'm getting confused, because somewhere else in my code I might need to reference this variable, and I cannot be sure when the callback will be called.

So how do we think when we deal with those things? Is there some tutorial or some videos out there that show in detail how to work with async programming with promises in JS?

Answer

Of course we can add a callback with then but I'm getting confused, because somewhere else in my code I might need to reference this variable, and I cannot be sure when the callback will be called.

You don't need to.

The "somewhere else code" will use .then() and yield a new promise for its result, relying on the pages promise. You can easily map the results, or chain other asynchronous tasks. Whenever you need to know about the timing of callbacks because of multiple dependencies, you should use your library's methods for composing promises, like all().

So how do we think when we deal with those things?

Think functional!

Every task in your program should explicitly and only depend on its inputs. A function should try to only use its arguments, not any global variables that contain state.

Is there some tutorial or some videos out there that show in detail how to work with async programming with promises in JS?

General Promise Resources in the wiki of the Q library is a very good start.