0

I have a method that must read an array to populate another in order to send it to other traitement...

I have do this :

    promiseArray: any[];
    new Promise((resolve, reject) => {
        if (myarray.length > 0) {
            myarray.forEach(itemArray => {
                this.create(anObject, anOtherObject).then(result => {
                    promiseArray.push(new MyObject(itemArray.file.name, itemArray.type, itemArray.ordre, result.urlFichier));
                    if (promiseArray.length === myarray.length) {
                        resolve();
                    }
                }, _ => {
                    this.alertService.error('error.transmission');
                });
            });
        } else {
            resolve();
        }
    }).then( _ => {
        .. Other Code
    }

This method must fill "promiseArray" with item from "myarray" but I have to use "result" from return of service "create"

create service is a method that return "Promise" :

        create(anObject: any, anOtherObject: myAnotherObject): Promise<any> {

        return new Promise<any>((resolve, _) => {
          this.AService(anObject.file,  myAnotherObject.id).subscribe(result2 => {
            if (result2) {
    
              const returnPromise = new AnotherObjectAgain();
              returnPromise.date = result2.body;
              resolve(returnPromise);
            } else {
              resolve(null);
              this.alertService.error('error.internalServer');
            }
          });
        });
      }

Then, when myarray is fill, i have to continue the code in the "Then" statement ...

My problem is that the "Then" statement is executed before the first promise is done and my array is totally fill (only one item is return when the "then" start).

Can you help me ?

Broshet
  • 133
  • 12

1 Answers1

0

You can't easily use forEach with async inside

You can either make it parallel with map

res = await Promise.all( list.map(e => asyncFunction(e)) )

or concurrent with for-of

for (let e of list) {
   res = await asyncFunction(e)
}

or get some library to work with array asyncroniously which starts iteration from the end of array because * u that's why, beware of that (true story)

Dimava
  • 7,654
  • 1
  • 9
  • 24