import { useState } from 'react';
export default function Form() {
const [text, setText] = useState('');
function sleep(milliseconds) {
const start = Date.now();
while (Date.now() - start < milliseconds) {
}
}
async function handleSubmit(e) {
sleep(5000);
}
function handleTextareaChange(e) {
setText(e.target.value);
}
return (
<>
<h2>Test</h2>
<form onSubmit={handleSubmit}>
<textarea
value={text}
onChange={handleTextareaChange}
/>
<br />
<button>
Submit
</button>
</form>
</>
);
}
I edited this component from the react docs to make it to the point.
I was learning react and JavaScript and ran into async functions in the react docs.
Here when I submit the form I can not edit it until the sleep runs out, but my confusion is that the sleep(5000) was called inside an async function.
Calling functions inside async functions does not make them non-blocking?
Or, does the form also call await on the handleSubmit as well?
My knowledge on JavaScript and react is low, so I may not be using terms correctly.
user22490316 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
4
Just because a function is called inside an async function, it doesn’t automatically make that function non-blocking. The function itself needs to be asynchronous or involve an asynchronous operation (like await or Promise-based operations) to avoid blocking.
function sleep(milliseconds) {
return new Promise((resolve) => setTimeout(resolve, milliseconds));
}
async function handleSubmit() {
await sleep(5000); // Non-blocking now because it's asynchronous
// other logic
}