I'm trying to develop a synchronous process in node.js, and I have implemented the async.series method, but the way of I've implemented is not working as I expect. I expect the second function of the series works after the first function terminate (including the operation of the loop). As the s3.getObject is an asynchronous function I'm a few lost how can I implement it correctly.

Resuming: I want to go to the second function after complete the loop and the functions inside the loop.

async.series([
  function(cback) {

    console.log("first function series...");

    for (var i = 0; i < jsonUsuariosPerfil.users.length; i++) {

      var usuario = jsonUsuariosPerfil.users[i];

      var paramsUsers = {
        Bucket: 's3.....br/.../users/' + usuario.user,
        Key: 'profiles',
      };

      console.log("loop jsonUsuariosPerfil... " + usuario.user);

      s3.getObject(paramsUsers, function(err, data) {

        if (err) {

          console.log("Error: " + err);
          const message = "Error getting user -> " + err;
          console.log(message);
          callback(message);

        } else {

          var jsonPerfisUsuario = JSON.parse(data.Body);

          var removido = false;

          console.log("found object..." + JSON.stringify(data.Body))

          for (var i = 0; i < jsonPerfisUsuario.profiles.length; i++) {

            var perfil = jsonPerfisUsuario.profiles[i];

            if (perfil.profile == id_grupo) {

              jsonPerfisUsuario.profiles.splice(i, 1);
              removido = true;
              break;

            }

          }

          if (removido) {

            var paramsPut = {
              Bucket: 's3.....br/.../users/' + usuario.user,
              Key: 'profiles',
              Body: JSON.stringify(jsonPerfisUsuario)
            };

            console.log("removido, salvando profiles");

            s3.putObject(paramsPut, function(err2, data2) {

              if (err2) {

                console.log("error putting the file:" + err2);

                var erro = {
                  status: "ERROR_SAVING_FILE"
                };

                generalCallback(null, erro);

              } else {

                console.log("salvo arquivo dos profiles do usuario");

              }

            });

          }

        }

      });

    }

    cback();
  },
  function(cback) {

    console.log("second function series...");

    removerGrupoCompleto();

  }

], function(err) {

  if (err) {
    var error = {
      status: "ERROR"
    };
    generalCallback(null, error);
  }

});

Log of what is happening:

pegou usuarios do perfil...

first function series...

loop jsonUsuariosPerfil... [email protected]

second function series..

Thanks a lot for all help.

share|improve this question
2  
And you aren't just chaining promises because...? – Jared Smith Feb 6 at 17:38
    
Hi Jared, I'm a beginner developer in javascript/ node.js and I didn't know what is this.. I'll search more about the "promises" thank you very much! – pedro.olimpio Feb 6 at 17:57
1  
Why was this tagged async-await? – Bergi Feb 6 at 18:33
    
@pedro.olimpio no problem, we were all beginners at some point: I didn't start programming professionally until I was in my 30s. One thing that you do need to learn though is how to suss out the nature of problems: in this case when you're trying to understand how to structure async code do the simplest async thing that could work. Its tempting to just jump in and try to solve the actual problem, but try to discipline yourself to produce a minimal example first. – Jared Smith Feb 6 at 18:53
    
@JaredSmith Thank you for your advises, really I managed to solve this issue with a simplest implementation, and was not really necessary to use async pack. Thank you again! – pedro.olimpio Feb 7 at 12:11

Couple of points to take care of:

  1. Always call callback, both in case of success as well as error.
  2. First argument of callback is error (In most of the cases)
  3. Use async.each or async.map to do asynchronous operation on each element of a collection

async.each(jsonUsuariosPerfil.users, processUser, function(err) {
  if (err) {
    var error = {
      status: "ERROR"
    };
    return generalCallback(error);
  } else {
    return generalCallback(null); // Always call callback and using with return is a good practice
  }
});

function processUser(usuario, callback) {
  var paramsUsers = {
    Bucket: 's3.....br/.../users/' + usuario.user,
    Key: 'profiles',
  };

  s3.getObject(paramsUsers, function(err, data) {
    if (err) {
      console.log("Error: " + err);
      const message = "Error getting user -> " + err;
      console.log(message);
      return callback(err);
    }

    var jsonPerfisUsuario = JSON.parse(data.Body);
    var removido = false;
    console.log("found object..." + JSON.stringify(data.Body))
    for (var i = 0; i < jsonPerfisUsuario.profiles.length; i++) {
      var perfil = jsonPerfisUsuario.profiles[i];
      if (perfil.profile == id_grupo) {
        jsonPerfisUsuario.profiles.splice(i, 1);
        removido = true;
        break;
      }
    }
    if (removido) {
      return removido(usuario, jsonPerfisUsuario, callback);
    }
    return callback();
  });
}

function removido(usuario, jsonPerfisUsuario, callback) {
  var paramsPut = {
    Bucket: 's3.....br/.../users/' + usuario.user,
    Key: 'profiles',
    Body: JSON.stringify(jsonPerfisUsuario)
  };
  console.log("removido, salvando profiles");
  s3.putObject(paramsPut, function(err2, data2) {
    if (err2) {
      console.log("error putting the file:" + err2);
      return callback(err2);
    }
    return callback();
  });
}
share|improve this answer
    
Reason for downvote, please. – Sangharsh Feb 6 at 19:20
    
Although I'm not the DV, I would guess its because the OP wants the async ops to run in succession, and you're still running them concurrently with async.each. – Jared Smith Feb 6 at 20:27

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.