Reputation: 4588
In my code, when I add the catch
, typescript shows the next error:
[ts] Type 'Promise' is not assignable to type 'Promise'. Type 'void | ItemEntity[]' is not assignable to type 'ItemEntity[]'. Type 'void' is not assignable to type 'ItemEntity[]'.
Also with only one then
and cath
I don´t the error.
The error appears when I use the two then
and the catch
together.
This is the code:
// HTTP GET
getAllItems(): Promise<ItemEntity[]> {
const request = new Request('http://localhost:4000/api/items', {
method: 'GET',
mode: 'cors',
redirect: 'follow',
headers: new Headers({
'Content-Type': 'text/plain'
})
})
return fetch(request)
.then( (response) => (response.json()) )
.then( (items) => (this.resolveMembers(items)) )
// FIXME
//.catch( (error) => (console.log(error)) );
}
private resolveMembers (data : any[]) : ItemEntity[] {
const items : ItemEntity[] = data.map((item) => {
let newItem : ItemEntity = new ItemEntity();
newItem.id = item.id;
newItem.task = item.task;
return newItem;
});
return items;
}
I have checked the functionality without catch on a node server and the GET works fine.
Upvotes: 1
Views: 329
Reputation:
It's telling you that you said your method is going to return a Promise<ItemEntity[]>
but you are trying to return Promise<void>
catch in the middle of a promise chain is meant to attempt to recover and continue on the chain. You should only catch what you can recover from otherwise let the error propagate up and let someone else catch it.
A simple recovery for your code would be to return an empty array. I would guess that subsequent calls to then would be able to handle an empty array.
return fetch(request)
.then( (response) => (response.json()) )
.then((items) => (this.resolveMembers(items)))
.catch((error) => {
console.log(error)
return []
})
Otherwise you can just not have your catch be part of the chain
var promise = fetch(request)
promise.catch(console.log)
return promise
.then( (response) => (response.json()) )
.then((items) => (this.resolveMembers(items)))
Upvotes: 4