I'm new to typescript, and I'm creating something and faced with problem that never happened when I use javascript.
Assume that we have async
function what returns Promise<ResultSet>
interface ResultSet {
status: number; // 0 for success 1 for failure
data?: any;
}
const getDataFromServer = async (parameter: string): Promise<ResultSet> => {
const response = await fetch(<--Prameters-->);
return await response.json();
}
It always returns it's value as Promise
.
And it need to be connected to interface so that some module can make use of this. It will change global variable's value using request above. And need to return result of action (success or failure code). And it's result of action used in lot's of place somewhere.
const storeData = async (parameter: string): number => {
const result = await getDataFromServer(parameter);
if (result.status == 0) {
SOME_GLOBAL_VARIABLE.setState({ data: result.data });
}
return result.status;
}
As you expect, the function definition above pops an error near async (parameter: string): number
cause function must returns Promise as it is async
function.
So it need to be below,
const storeData = async (parameter: string): Promise<number> => {
const result = await getDataFromServer(parameter);
if (result.status == 0) {
SOME_GLOBAL_VARIABLE.setState({ data: result.data });
}
return result.status;
}
The problem begin with this. Cause return type of function is Promise
, all other functions' interfaces connected with this must define that result status as Promise<number>
not a number
. And it will globally effected to entire server code.
Also, that SOME_GLOBAL_VARIABLE
's data
also need to be typed as Promise<T>
.
As I know, there are no way to convert promise object to normal object.
I want to cut this endless chainning of promises. Is there any way? or is it just my misunderstanding? Even replacing async ~ await
to then() ~ catch()
also failed, because it seems it also returns Promise
.
The Promise
guarantee if it's value is successfully resolve or not. But, in some point, it is already guaranteed as Resolve. But there's no way to handle this situation.
How can I deal with this situation? This seems really common case when using typescript. But i don't know how to do.
fetch
and subsequent callbacks doesn't change from JavaScript to TypeScript. In both JavaScript and TypeScript you'll still need to eitherawait
the Promise or use athen
callback. You shouldn't need to change the typing ofSOME_GLOBAL_VARIABLE
toPromise<T>
because that's after the async part, therefore the data is already resolved. – Paul