Contents

Async and Await

Async and Await

Async and Await
  • Async and wait make promises easier to write.
  • Async make a function to return a promise.
  • Await makes function to wait for a promise.
  • Async and Wait is the exetension of promises.
Async
Async simply allows us to make promise based code as if it was synchronous and it check that we are not breaking the execution thread. It operates asynchronously via the event loop. Async functions will always return value. It make sure that promise returned otherwise automatically wraps it in a promise which is resolved with its value.
Await
Await function is used to await for the promise it could be used within the async block only.It makes the code wait until the promise return result.
                    
                      const url = "https://randomuser.me/api";
                      const userData = async () => {
                        fetch(url)
                          .then((response) => {
                            if (response.status === 200) {
                              return response.json();
                            } else {
                              throw new Error("Something went wrong");
                            }
                          })
                          .then((data) => {
                            const users = data.results;
                            // console.log(users);
                            setData(users);
                          })
                          .catch((error) => {
                            console.log(error);
                          });
                      };
                      useEffect(() async => {
                        const data = await userData();
                      }, []);