如何使用角度2返回承诺的值

时间:2016-08-24 13:36:13

标签: angular typescript ionic2 ionic3

这是我的promise函数,我需要返回rs.rows.item(0);

的值
     public getCustomer()  : any
  {
        let  db =  window.sqlitePlugin.openDatabase({name: 'data.db', location: 'default'});
        return new Promise((resolve, reject) =>
        {
            db.transaction(function(tx)
            {
                tx.executeSql('SELECT * FROM customer ORDER BY customerId DESC LIMIT 1', [], function(tx, rs)
                {
                     return resolve(rs.rows.item(0));
                }, 
                function(tx, error) 
                {
                    console.log('SELECT error: ' + error.message);
                    reject(error);
                });
            });
        });    
  }

返回值我得到了一个像这个图像image result

的对象

我需要得到这样的例子

var customer = getCustomer();
customer.name;
customer.email;

4 个答案:

答案 0 :(得分:6)

Promises 为我们提供了抽象,帮助我们处理应用程序的异步性质。由于我们不知道这些操作需要多长时间(因此,数据何时可用),因此您需要使用then()方法在准备好使用数据时执行某些代码:

this.getCustomer()
    .then((data) => {
        // Here you can use the data because it's ready
        // this.myVariable = data;
    })
    .catch((ex) => {
        console.log(ex);
    });

答案 1 :(得分:1)

首先,您需要func来获取所有数据:

getAll(): Promise<Phrase[]> {
        return phrasesPromise;
    }

第二,如果您需要一件物品,可以使用

ngOnInit() {
        this.phraseService
            .getAll()
            .then(result => this.phrases = result);
    }

答案 2 :(得分:1)

您可以像这样使用await operator

getCustomer(): Promise<any> {
    [...]
}

async functionThatNeedsCustomer() {
    const customer = await getCustomer();
    const name = customer.email;
    const email = customer.email;
}

等待操作符唤醒形成Promise以返回结果。 这只能在异步函数内部完成(使函数异步将使其自身返回promise)。

答案 3 :(得分:1)

这是一个Promise,因此您需要使用then

getCustomer()
    .then(customer => {
        customer.name;
        customer.email;
    });

如果您使用的是TypeScript或支持async / await的JavaScript版本,则可以执行以下操作:

var customer = await getCustomer();
customer.name;
customer.email;

上面的代码需要在async函数中,就像这样:

async displayCustomerDetails() {
    var customer = await getCustomer();
    customer.name;
    customer.email;
}