2
Good morning. I wonder if it is possible to define the return type of a Promise with typescript. I need this because I have a function that returns a precedent for a query in the database and I need that when the query is performed the return is an object (in my case a product), but then() returns a Unknown type. An example of the code that returns to Promise is attached:
getProtudo(idProduto) {
return new Promise((res, rej) => {
this.bancoSrc.banco.find({
selector: {type: 'produto', _id: idProduto},
fields: ['_id', 'descricao', 'referencia']
}).then((result) => {
this.produto = JSON.parse(result);
res(this.produto);
}).catch(err => {
rej(err);
});
});
}
And here’s the code that uses that code:
this.pickerCtrl.create(opts).then((picker) => {
picker.present();
picker.onDidDismiss().then(async (data) => {
const col = await picker.getColumn('quantidade');
this.produtoSrc.getProtudo(idProduto).then((prod) => {
const qtd = col.options[col.selectedIndex].value;
const pedido: Produto = new Produto(prod._id, prod.descricao, qtd, 10);
this.listaPedido.add(pedido);
});
});
});
}
I cannot create the object because when having to use the Prod. _id no create of my object, gives the following error: ": "Property '_id' does not exist on type 'Unknown'.
That way I posted up this working. But now I have another doubt, my object is coming as Undefined when I try to access its properties. Function:
getProtudo(idProduto) {
return new Promise<Produto> ((res, rej) => {
this.bancoSrc.banco.find({
selector: {type: 'produto', _id: idProduto},
fields: ['_id', 'descricao', 'referencia']
}).then((result) => {
res(result);
}).catch(err => {
rej(err);
});
});
}
If I display it behind the console it displays the following response:
docs: Array(1)
0: {_id: "produto-1", descricao: "LANTERNA DIANT DIR", referencia: "KADETTE"}
length: 1
__proto__: Array(0)
__proto__: Object
Can anyone help me with that? Thanks in advance.
Gustavomgu, your method
getProtudo
is returning an array, so you are not able to access the property_id
directly. Since its function should only return one object, instead of doingres(result)
, dores(result[0])
. Maybe you need to do theJSON.parse
also as you were doing in the first example.– Andre
You’re right, it was an array, to be able to access it I used result.Docs[0]. (I had to do this because I’m retrieving the information from a Nosql database)
– Gustavomgu.developer