The getUnansweredQuestions function doesn't simulate a web API call very well because it isn't asynchronous. In this section, we'll change this. Follow these steps to do so:
- Open QuestionsData.ts and create an asynchronous wait function that we can use in our getUnansweredQuestions function:
const wait = (ms: number): Promise<void> => {
return new Promise(resolve => setTimeout(resolve, ms));
};
This function will wait asynchronously for the number of milliseconds we pass into it. The function uses the native JavaScript setTimeout function internally, so that it returns after the specified number of milliseconds.
Notice the function returns a Promise object.
Notice the <void> after the Promise type in the return type annotation. Angle brackets after a TypeScript type indicate that this is a generic type.
We are passing a void type into the generic Promise type. But what is the void type?
- Now, we can use the wait function in our getUnansweredQuestions function to wait half a second:
export const getUnansweredQuestions = async (): Promise<QuestionData[]> => {
await wait(500);
return questions.filter(q => q.answers.length === 0);
};
Notice the await keyword before the call to the wait function and the async keyword before the function signature.
We return a Promise<QuestionData[]> rather than QuestionData[] because the function doesn't return the questions straight away. Instead, it returns the questions eventually.
- So, the getUnansweredQuestions function is now asynchronous. If we open HomePage.tsx, which is where this function is consumed, we'll see a compilation error:
This is because the return type of the function has changed and no longer matches what we defined in the QuestionList props interface.
- For now, let's comment the instance of QuestionList out so that our app compiles:
{/* <QuestionList data={getUnansweredQuestions()} /> */}
Eventually, we're going to change HomePage so that we store the questions in the local state and then use this value in the local state to pass to QuestionList. To do this, we need to invoke getUnansweredQuestions when the component is first rendered and set the value that's returned to state. We'll do this in the next section.