D
D
djok21422021-02-21 15:07:22
JavaScript
djok2142, 2021-02-21 15:07:22

How to make a sequence of loop iterations with asynchronous code?

Good afternoon.
I'm learning node.js, after synchronous php it's a bit difficult but very interesting.

There is this simplified code example:

db.query(" SELECT * FROM users LIMIT 0,100 ", function(err, result) {
  for( row of result ) {
    request('https://site.ru/api/', function (error, response, body) {
      db.query(" UPDATE users SET some_field='"+body+"' WHERE id='"+row['id']+"' ", function(err, result) {
        console.log('User updated');
      });
      
    });
  }
});

In this code, records are selected from the database, then it is cycled through, and for each record, a request is made to the api of a third-party site, after receiving a response, the corresponding row in the database is updated. So, I can’t figure out how to make each next iteration of the for loop occur only after the request and db asynchronous functions are executed, that is, so that requests to the site go strictly sequentially, but now everything happens in parallel. Most likely, instead of for, you need to use something else, or something using promises, I can’t figure it out.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
djok2142, 2021-02-22
@djok2142

db.query(sql, async function(err, result) {
  for( let row of result ) {
    let promise = new Promise((resolve, reject) => {
      request(url, function (error, response, body) {
        db.query(sql, function(err, result) {
          console.log('User updated');
          resolve();
        });
        
      });
    });

    let result = await promise;
  }
});

V
Vladimir, 2021-02-21
@AstraVlad

There is a lot written about it here:
How to work with async/await in JavaScript loops

0
0xD34F, 2017-10-24
@vovandon

An error in the calculation . Do not do it this way. There is scrollY - you can use it. $(window).offset()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question