【问题标题】:synchornous code in angularjs [duplicate]angularjs中的同步代码[重复]
【发布时间】: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.createdb.executeSql 返回的内容。您需要向调用者返回一个承诺,以便调用者 (getCustomerById) 可以订阅它。

标签: javascript angularjs ionic2


【解决方案1】:

你能发布来自 SqliteProvider 方法的代码吗? 我很确定它会返回 PromiseObservable

Promises 和 Observables 的问题是调用者必须等到他们完成工作,然后在闭包方法中继续。

所以你应该做如下的事情:

this.SP.getCustomerById(this.id).then((customer) => {
    this.SP.customerById = customer;
    alert(this.SP.customerById);
}, error => {console.log(error)});

请注意,如果您的 SqliteProvider 方法返回 Observable 而不是 Promise,则必须相应地更改代码(添加 subscribe而不是 然后)

您可以阅读关于 Promises here 和 Observables 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中添加了函数
  • 查看编辑后的答案
猜你喜欢
  • 2013-01-28
  • 1970-01-01
  • 1970-01-01
  • 2013-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-18
相关资源
最近更新 更多