代码是在Ionic框架中的Angularjs中编写的。我认为Angular背景的人也可以回答这个问题。angularjs中的synchornous代码
当我调用这个函数时,alert分别显示空数组“[]”和“undefined”。我认为这是JavaScript异步性质的原因。我想要这个函数同步执行。
/*This is the constructor */
constructor(public navCtrl: NavController, public SP: SqliteProvider) {
}
/*my function*/
getCustomerById()
{
this.SP.getCustomerById(this.id);
this.customerById = this.SP.customerById;
alert(this.SP.customerById);
alert(this.SP.customerById[0]);
}
/*中SqliteProvider功能*/
getCustomerById(cid)
{
this.customerById = [];
this.sqlite.create({
name: this.dbName,
location: 'default'
})
.then((db: SQLiteObject) =>{
db.executeSql('SELECT * FROM `customers` WHERE id= ?', [cid])
.then(result => {
var json = JSON.parse(result.rows.item(0).json);
//alert(json);
this.customerById.push(json);
// alert(JSON.stringify(this.customerObject));
})
.catch(e => console.log(e));
})
.catch(e => console.log(e));
}
'我想这个函数执行synchronously' <= **不,你不要**你只是不知道如何正确使用异步调用。阅读上述重复链接的答案,特别是名为** ES2015 +的标题:使用then()**承诺,类似于'sqllite.create'和'db.executeSql'返回的内容。你需要向你的调用者返回一个承诺,以便调用者(getCustomerById)可以订阅它。 – Igor