Циклическая асинхронная функция внутри двухцепной асинхронной функции и внутри другого цикла - PullRequest
0 голосов
/ 08 ноября 2018

У меня есть 3 асинхронных функции, обернутых в loop1, внутри первые 2 асинхронные функции объединены в цепочку после успешного выполнения каждой из первых 2 функций, последняя асинхронная функция обернута другим циклом. Это будет проблемой, цикл не будет ждать 3-й асинхронной функции для выполнения и возврата значения перед повторным циклом.

код ts, который будет вызывать провайдер, это цикл 1

for(var i=0; i<maxValue; i++){
    if(this.loanSteps.length > i){
       this.localdb.insertStepsToApply(this.loanSteps[i]);
      }
    }

код функции провайдера

  insertStepsToApply(stepsValue){
    return this.sqlite.create({
      name: 'govservices.db',
      location: 'default'
    }).then((db: SQLiteObject) => {
      return db.executeSql('INSERT INTO application_steps(steps_program_refer_id,steps) VALUES ('+this.governmentprogram_id+',"'+stepsValue+'")',[])
      .then(res=>{
        console.log('inserted steps');   
        return db.executeSql('SELECT * FROM application_steps ORDER by appsteps_id DESC LIMIT 1', [])
        .then(async res=>{
          if(res.rows.length > 0){
              this.applyStepsid = res.rows.item(0).appsteps_id;
              console.log('extracting app steps id ->'+this.applyStepsid);
              var steplength = stepsValue.split(/\r\n|\r|\n/).length; // new line
              var stepLengthblankspace = (stepsValue.match(/^[ \t]*$/gm) || []).length; // blank spaces
              var numberOfSentences = steplength - stepLengthblankspace;

              for(var ix=0; ix < numberOfSentences; ix++){
                await db.executeSql('INSERT INTO requirement_list(requirement_government_program_id, requirement_steps_id) VALUES ('+this.governmentprogram_id+','+this.applyStepsid+')',[])
                .then(res =>{
                  alert('successfully inserted to steps apply requiermeent box');
                    return res;
                  }).catch(e =>{
                    console.log(e.message); 
                  });
              }
          }
        }).catch(e => console.log(e.message));
      }).catch(e => console.log(e.message));
    }).catch(e => console.log(e.message));
  }

обратите внимание, что внутренний цикл будет зависеть от того, сколько предложений содержит значение шагов, это значение шага является текстовым полем и содержит абзац ожидаемый результат, который я хочу, выглядит так

inserted steps
extracting app steps id -> 3
successfully inserted to steps apply requirement box
successfully inserted to steps apply requirement box
successfully inserted to steps apply requirement box
inserted steps
extracting app steps id -> 4
successfully inserted to steps apply requirement box
successfully inserted to steps apply requirement box

но на самом деле это так

inserted steps
extracting app steps id -> 3
inserted steps
extracting app steps id -> 4
successfully inserted to steps apply requirement box
successfully inserted to steps apply requirement box
successfully inserted to steps apply requirement box
successfully inserted to steps apply requirement box
successfully inserted to steps apply requirement box

Я также помещаю обещание вне внутреннего цикла (loop2), но все же вывод не верен, есть идеи о том, как обрабатывать что-то подобное?

1 Ответ

0 голосов
/ 09 ноября 2018

просто решите мою проблему, как то, что предложил @Kokodoko, создав еще одну функцию для чего-то подобного

    return db.executeSql('SELECT * FROM application_steps ORDER by appsteps_id DESC LIMIT 1', [])
    .then(async res=>{
      if(res.rows.length > 0){
          this.applyStepsid = res.rows.item(0).appsteps_id;
          console.log('extracting app steps id ->'+this.applyStepsid);
          var steplength = stepsValue.split(/\r\n|\r|\n/).length; // new line
          var stepLengthblankspace = (stepsValue.match(/^[ \t]*$/gm) || []).length; // blank spaces
          var numberOfSentences = steplength - stepLengthblankspace;
          console.log('total sentences '+numberOfSentences+' = '+steplength+' - '+stepLengthblankspace);
          for(var ix=0; ix < numberOfSentences; ix++){
            await this.insertIntoRequirementCheckbox();
          }
      }
    }).catch(e => console.log(e.message));

insertIntoRequirementCheckbox(){
return this.sqlite.create({
  name: 'govservices.db',
  location: 'default'
}).then((db: SQLiteObject) =>{
  return db.executeSql('INSERT INTO requirement_list(requirement_government_program_id, requirement_steps_id) VALUES ('+this.governmentprogram_id+','+this.applyStepsid+')',[])
  .then(res =>{
    console.log('requirement checkbox successfully inserted');
    }).catch(e => console.log(e.message));
  }).catch(e => console.log(e.message));
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...