8

这是我需要返回 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);
                });
            });
        });    
  }

返回值我得到了一个像这张图片的对象图像结果

我需要像这个例子

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

4 回答 4

8

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

this.getCustomer()
    .then((data) => {
        // Here you can use the data because it's ready
        // this.myVariable = data;
    })
    .catch((ex) => {
        console.log(ex);
    });
于 2016-08-25T11:16:21.620 回答
3

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

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

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

ngOnInit() {
    this.phraseService
        .getAll()
        .then((result: Phrase[]) => this.phrases = result);
}
于 2017-10-20T20:27:34.437 回答
3

这是一个Promise,所以你需要使用then

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

如果您使用的是 TypeScript 或支持async/的 JavaScript 版本await,您可以这样做:

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

以上将需要在一个async函数中,如下所示:

async displayCustomerDetails() {
    var customer = await getCustomer();
    customer.name;
    customer.email;
}
于 2018-10-10T10:40:51.323 回答
1

您可以像这样使用await 运算符

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

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

await 操作符从 Promise 中等待返回结果。这只能在异步函数内部完成(使函数异步将使其返回一个承诺本身)。

于 2018-10-10T07:02:40.867 回答