【发布时间】:2018-11-09 14:38:46
【问题描述】:
我有 3 个异步函数由一个循环 1 包装,在成功执行前 2 个函数后,前 2 个异步函数被链接起来,最后一个异步函数用另一个循环包装。这将是问题所在,循环不会等待第三个异步函数执行并返回一个值,然后再次循环。
将调用提供者的 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));
}
注意,内部循环将取决于steps值有多少个句子,这个stepvalue是一个文本框并且有一个段落 我想要的预期输出是这样的
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)之外放置了promise,但输出仍然不正确,知道如何处理这样的事情吗?
【问题讨论】:
-
只是我的 2 美分;当您的代码开始变得如此复杂时,通常最好将其拆分为可以单独测试的单独函数。
-
@Kokodoko 那会更好,我想我会试试的
-
尽量不要将
then与await语法混用。
标签: javascript typescript asynchronous ionic-framework