Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using 'Promise' vs. NOT using 'Promise' : in which cases?

I don't know if SO is the right place for such a question.

I know a bit Promises, and I use them in a Node/Express environment to 'fix' the asynchronous behavior of Node when querying database (= Wait for DB answer, then do something).

However, the more I use them, the less I know when not use them.

For example, I wrote a piece of code like this (for a local script querying Google Matrix API)...

 ....
 for (var i = 0; i < rows.length; i++) { // loop over a CSV file by line
    var cell = rows[i].split(/;/)
    var origin = cell[1]
    var destination = cell[2]
    var id = cell[0]
    Promise.all([origin, destination, id]).then((p) => {}
 ...

I don't know if using here a Promise.all makes sense at all...

Is there a rule to know? A behavior I do not get?

Say differently, when do I know there is a "risk" that my script runs a function without its right argument (argument being returned from another function which is not "over") ...?

Thanks.

like image 371
charnould Avatar asked Oct 18 '22 19:10

charnould


1 Answers

When you have entirely synchronous code (no async operations you are trying to track the completion of), you do NOT want to use promises.

Trying to use promises with synchronous code only adds unnecessary complication to the logic of the code and slows down the execution of your code. With all synchronous code, there is nothing to wait for the completion of or to coordinate with the completion of so you can just execute your code and have the result immediately. Adding promises just complicates your code unnecessarily.

In addition, Promise.all() expects that you pass it an array of promises, not an array of values like you are doing so in addition to be unnecessary, what you were doing was also incorrect.

So, there's really no reason to not just do this:

 ....
 for (var i = 0; i < rows.length; i++) { // loop over a CSV file by line
    var cell = rows[i].split(/;/)
    var origin = cell[1]
    var destination = cell[2]
    var id = cell[0]
    // operate on id, destination and origin here
    // no need to wait on a promise before doing so
 }
 ...

Promise would be used with asynchronous operations such as database operations, file operations, networking operations, timing operations, etc... You can use them to either know when an individual asynchronous operation is done or to coordinate multiple operations (some of which are asynchronous).

like image 157
jfriend00 Avatar answered Oct 20 '22 09:10

jfriend00