angularjs中的synchornous代码
代码是在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));
}
你能员额从SqliteProvider方法的代码? 我很确定它会返回Promise或Observable。
Promise和Observables的事情是,调用者必须等到他们完成他们的工作,然后在关闭方法中继续。
所以,你应该做的事情如下所示:
this.SP.getCustomerById(this.id).then((customer) => {
this.SP.customerById = customer;
alert(this.SP.customerById);
}, error => {console.log(error)});
注意,如果您SqliteProvider方法返回一个可观察,而不是一个无极,你将不得不相应地更改代码(添加订阅而不是然后)
你可以阅读Promises here的令人敬畏的教程和Observabl es here。
编辑后发布方法:
也this answer见。 实际上不需要有一个内部customerById变量。 其实它不是一个好的做法,因为你的方法只应该检索客户,而不是把它分配给一个变量。 你应该改变你的代码如下:
getCustomerById(cid)
{
return
this.sqlite.create({
name: this.dbName,
location: 'default'
})
.then((db: SQLiteObject) =>{
return
db.executeSql('SELECT * FROM `customers` WHERE id= ?', [cid])
.then(result => {
return JSON.parse(result.rows.item(0).json);
})
.catch(e => console.log(e));
})
.catch(e => console.log(e));
}
我在说明中加了这个功能@paul –
查看编辑的答案 –
'我想这个函数执行synchronously' Igor