Promise, await/async ou callback

monpseudolionel -  
 Utilisateur anonyme -
Bonjour à tous,

Depuis quelques années, je n'ai pas développé en JS et j'ai besoin de reprendre un script tout simple mais il ne exécute pas dans l'ordre.

Le voici :

getNotificationSounds2(serialOrName, idSound, callback)
{
console.log("1");
let result="";
this.getNotificationSounds(serialOrName, (err, res) =>
{
console.log("2");
res.notificationSounds.forEach(function(item, index) {
if (item['id'] == idSound) {
result=item;
console.log("3");
}
});
});
console.log("4");
return result;
}

**Modifié par la modération pour une lecture plus facile du code, à l'avenir utilisez les balises, VOIR CETTE PAGE

Je me retrouve avec 1 puis 4 puis 2 puis 3

Je sais c'est l'erreur classique de JS en synchrone / asynchrone et j'imagine que c'est tout simple à changer mais j'ai passé l'après midi a essayer de retrouver comment faire.

Une bonne âme pourrait m'aider ?

Merci

1 réponse

  1. Utilisateur anonyme
     
    Salut,

    avec la callback,

    function getNotificationSounds2(serialOrName, idSound, callback) {
      console.log("1");
    
      this.getNotificationSounds(serialOrName, (err, res) => {
        if (err) {
          console.log(err);
          return;
        }
        
        res.notificationSounds.forEach(function (item, index) {
          if (item['id'] == idSound) {
            callback(item);
          }
        });
      });
    }
    
    getNotificationSounds2('plock', 1, (result) => {
      console.log(result);
    });
    


    Avec un promesse:

    const getNotificationSounds2 = (serialOrName, idSound) => new Promise((resolve, reject) => {
      this.getNotificationSounds(serialOrName, (err, res) => {
        if (err) {
          reject(err);
        }
    
        res.notificationSounds.forEach((item, index) => {
          if (item['id'] == idSound) {
            resolve(item);
          }
        });
    
        reject(new Error("Not found"));
      });
    });
    
    getNotificationSounds2('plock', 1)
    .then((result) => {
      console.log(result);
    }).catch((err) => {
      console.log(err);
    });
    
    
    0