【发布时间】:2018-03-31 07:35:56
【问题描述】:
代码是在 Ionic 框架中用 Angularjs 编写的。我认为来自 Angular 背景的人也可以回答这个问题。
当我调用此函数时,警报分别显示空数组“[]”和“未定义”。我认为这是由于 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));
}
【问题讨论】:
-
I want this function to execute synchronously不,你不知道。你只是不知道如何正确使用异步调用。阅读上面重复链接的答案,特别是名为 ES2015+: Promises with then() 的标题,它类似于sqllite.create和db.executeSql返回的内容。您需要向调用者返回一个承诺,以便调用者 (getCustomerById) 可以订阅它。
标签: javascript angularjs ionic2