-1

I got this method demandeCreationCours. At first, I create an array of courses ( let listeCours1 = new Array();

what I'm doing is, I'm actually calling an api for some information (local api), with that information, I'm creating an object and putting into my array listeCours1. At the end of the call, I'm keeping a console.log of array size. At first I thought I didn't get any information from my api but then I print what I got and I saw that I got information. Maybe someone know what is the problem lies here in this regard.

Bellow, is my demandeCreationCOurs method.

 public demandeCreationCours() {
        let prof = (Utilisateur.getUtilisateurConnecte() as Enseignant);
        let listeCours1 = new Array<Cours>();



        if (prof === undefined) {
            // L'enseignant n'existe pas
            throw new NotFoundError("Enseignant '" + "' n'existe pas.");
        }

        const options = {
            port: 3001,
            path:'http://127.0.0.1/api/v1/courses',
            method: 'GET',
            headers: {
                'token': prof.getTokenUserConnected(),
                'Content-type': 'application/json'
            }
        };


        http.get(options , (resp) => {
            var str = '';

            let data = '';
            
            // A chunk of data has been received.
            resp.on('data', (chunk) => {
                data += chunk;
            });
          
            // The whole response has been received. Print out the result.  
            resp.on('end', ()  => {
                
                let listCours = JSON.parse((JSON.parse(data).data));

                // on créer une instance pour chaque cours qui existe dans SGB, et on l'ajoute a la map de cours de l'Enseignant
                for(let i = 0 ; i < listCours.length ; i++){
                    console.log(''+listCours[i]._id);
                    listeCours1.push(new Cours(''+listCours[i]._sigle as string, ''+listCours[i]._titre as string,listCours[i]._groupe as number, ''+listCours[i]._id as string))
                    prof.addCours(new Cours(listCours[i]._sigle as string, listCours[i]._titre as string,listCours[i]._groupe as number, ''+listCours[i]._id as string));
                }
                
            });
        });

        console.log("La liste des cours dans controleur gerer cours : " + listeCours1.length)
        console.log("La liste des cours du prof dans controleur gerer cours : " + prof.mapCours.size)


        return listeCours1;

    }
Salahuddin Ahmed
  • 4,854
  • 4
  • 14
  • 35
  • 1
    This looks like a basic async issue. You are only guaranteed to have the data from the API after the callback to the `get` is executed. This means that the lines outside of the `get` are not going to have the data as the API call has not been made and/or returned data *yet*. – crashmstr Mar 05 '21 at 18:32
  • 2
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – crashmstr Mar 05 '21 at 18:33

1 Answers1

0

Might this work?

 public demandeCreationCours() {
        let prof = (Utilisateur.getUtilisateurConnecte() as Enseignant);
        let listeCours1 = new Array<Cours>();



        if (prof === undefined) {
            // L'enseignant n'existe pas
            throw new NotFoundError("Enseignant '" + "' n'existe pas.");
        }

        const options = {
            port: 3001,
            path:'http://127.0.0.1/api/v1/courses',
            method: 'GET',
            headers: {
                'token': prof.getTokenUserConnected(),
                'Content-type': 'application/json'
            }
        };

        await new Promise((resolve, reject) => {
          http.get(options , (resp) => {
              var str = '';

              let data = '';
              
              // A chunk of data has been received.
              resp.on('data', (chunk) => {
                  data += chunk;
              });
            
              // The whole response has been received. Print out the result.  
              resp.on('end', ()  => {
                  
                  let listCours = JSON.parse((JSON.parse(data).data));

                  // on créer une instance pour chaque cours qui existe dans SGB, et on l'ajoute a la map de cours de l'Enseignant
                  for(let i = 0 ; i < listCours.length ; i++){
                      console.log(''+listCours[i]._id);
                      listeCours1.push(new Cours(''+listCours[i]._sigle as string, ''+listCours[i]._titre as string,listCours[i]._groupe as number, ''+listCours[i]._id as string))
                      prof.addCours(new Cours(listCours[i]._sigle as string, listCours[i]._titre as string,listCours[i]._groupe as number, ''+listCours[i]._id as string));
                  }
                  
                  resolve(data);
              });
          });
        })

        console.log("La liste des cours dans controleur gerer cours : " + listeCours1.length)
        console.log("La liste des cours du prof dans controleur gerer cours : " + prof.mapCours.size)


        return listeCours1;

    }
md2perpe
  • 3,372
  • 2
  • 18
  • 22