Как заставить цикл for ждать, пока база данных firebase не будет вставлена ​​с помощью обещаний - PullRequest
0 голосов
/ 20 июня 2019

Я вставляю массив данных в базу данных Firebase.Проблема, с которой я столкнулся, заключается в том, что я должен сделать вызов базы данных Firebase внутри этого итерационного кода, в результате чего, хотя строка успешно создается для каждого значения объекта, значение, введенное в каждую строку, всегда одинаково (последнее значение в массиве объектов).

Я уже пробовал этот метод и не работает: https://stackoverflow.com/a/42343907/1014250


submitted() {

    if (!this.nestedForm.valid) {
          alert('Please fill the forms');

    } else {
     this.id = this.generateUUID();
      const id = this.id;

      const permitnumber = this.nestedForm.value.permitnumber;
      const permitdate = this.nestedForm.value.permitdate;
      const incomingdate = this.nestedForm.value.incomingdate;
      const storename = this.nestedForm.value.storename;
      const explosivesarr = this.nestedForm.value.address;
      const detonator = this.nestedForm.value.detonator;
      const accessories = this.nestedForm.value.accessories;
      console.log("explosivesarr"+explosivesarr)
      explosivesarr.forEach(async element => {
        this.explosivename = element.explosive;
        this.qty = element.qty;
        this.unit = element.unit;
           this.product = this.productDetails.find(o => o.productname === element.explosive)

        if(this.product){
          const productid = this.product.id;
          this.quantityinstore = this.product.totalquantity;

          this.totalquantity = Number.parseFloat(this.quantityinstore.toString())  +  Number.parseFloat(this.qty.toString());

           this.db.createincomingoperation(id,this.uuid, permitnumber, permitdate,incomingdate ,
            storename,explosivesarr,detonator,accessories).then(() =>  {

              this.db.updateincomingoperation(productid,this.totalquantity)
              .then(() => {
                alert('incoming operation added successfully');

               });

            });

        }
       else if(!this.product){
         this.quantityinstore = 0;
         this.totalquantity = Number.parseFloat(this.quantityinstore.toString())  +  Number.parseFloat(this.qty.toString());
        await this.db.createincomingoperation(id,this.uuid, permitnumber, permitdate,incomingdate,
            storename,explosivesarr,detonator,accessories).then(() =>  {
            this.db.insertincomingoperation(
                id,
                this.explosivename,
                this.qty,
                this.unit,
                permitnumber,
                permitdate,
                incomingdate,
                storename,
                this.totalquantity)

                .then(() => {
                  alert('incoming operation added successfully');
                   this.id = this.generateUUID();
                 });
            });


        }

        });

      }

  }

Служба базы данных

createincomingoperation(id,uuid, permitnumber, permitdate,incomingdate ,storename,explosivesarr,detonator,accessories): Promise<void> {
              const dateTime = new Date().toISOString(); 
              const status = 'On Delivery';
              const color = '#FF8C00'; //orange
              return this.db.doc(`productmeterials_logs/${id}`).set({
              id,uuid,permitnumber,permitdate,incomingdate, storename,   explosivesarr,
              detonator,
              accessories,
              color,
              dateTime,
              status,
               });
              }

              updateincomingoperation(id,totalquantity): Promise<void>  {  
                          return this.db.doc(`productmeterials/${id}`).update({
                              totalquantity 
                            });
                            }


              insertincomingoperation(
                           id,
                          productname,
                          qty,
                          unit,
                          permitnumber,
                          permitdate,
                          incomingdate,
                          storename,
                          totalquantity): Promise<void> {          
                         const date: string = new Date().toISOString();
                            const method = 'incoming';
                              return this.db.doc(`productmeterials/${id}`).set({
                                id,
                                method,
                                productname,
                                qty,
                                unit,
                                permitnumber,
                                permitdate,
                                incomingdate,
                                storename,
                                totalquantity

                              });
                              }


Этоне дожидается вставки данных.

1 Ответ

0 голосов
/ 21 июня 2019

Вы не можете использовать метод .forEach, если хотите, чтобы он ждал.

Попробуйте это:

for(const element of explosivesarr) {
   await yourDbCall();
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...