2017-10-19 36 views
0

代码是在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)); 
} 
+0

'我想这个函数执行synchronously' <= **不,你不要**你只是不知道如何正确使用异步调用。阅读上述重复链接的答案,特别是名为** ES2015 +的标题:使用then()**承诺,类似于'sqllite.create'和'db.executeSql'返回的内容。你需要向你的调用者返回一个承诺,以便调用者(getCustomerById)可以订阅它。 – Igor

回答

0

你能员额从SqliteProvider方法的代码? 我很确定它会返回PromiseObservable

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)); 
} 
+0

我在说明中加了这个功能@paul –

+0

查看编辑的答案 –