I'm new on Typescript
How can I read the function json response from my callback function?
this is my function, it return html content...
async function getContent(src: string) {
try {
const response = await fetch(src);
if (!response.ok) {
throw new Error(`Error! status: ${response.status}`);
}
const result = { content: await response.text(), correlationId: response.headers.get("x-correlationid") };
return result;
} catch (error) {
if (error instanceof Error) {
return error.message;
} else {
return 'An unexpected error occurred';
}
}
}
And this is the way I'm trying to read the json from response. But result.json() is highligthed in red with error "Property json does not exists on type string"
getContent(src)
.then( result => result.json())
.then( post => {
iframe.contentDocument.write(post.content);
})
.catch( error => {
console.log(error);
});
***** UPDATE ******
The problem was inside my getContent function, the catch block must return errors in the same object structure.
function updated
async function getContent(src: string) {
try {
const response = await fetch(src);
if (!response.ok) {
throw new Error(`Error! status: ${response.status}`);
}
const result = { content: await response.text(), correlationId: response.headers.get('x-correlationid') };
return result;
} catch (error) {
if (error instanceof Error) {
return { content: error.message, correlationId: undefined };
} else {
return { content: 'An unexpected error occurred', correlationId: undefined };
}
}
}
and the function call
getContent(src)
.then( result => {
iframe.contentDocument.write(result.content);
console.log(`I have the correlation ${result.correlationId}`);
})
.catch( error => {
console.log(error.content);
});