Dino Geek, try to help you

How to run JavaScript asynchronously with Async/Await?


In JavaScript, the `async` function returns a promise which can be used with the `await` expression to pause to wait for the promise’s resolution or rejection.

This feature is used with asynchronous functions to simplify the behavior of using promises synchronously and to perform some behavior on a group of Promises.

An `async` function can contain an `await` expression that pauses the execution of the `async` function and waits for the passed Promise’s resolution, then resumes the `async` function’s execution and returns the resolved value.

Here is a basic example showing how to use async/await:

```
async function fetchData() { try { const response = await fetch(‘http://example.com/data’); const data = await response.json(); console.log(data); } catch (error) { console.log(‘error: ‘, error); }
}

fetchData();
```

In the example above:

1. `fetchData()` function is declared as `async` which means it will return a Promise.
2. Inside `fetchData()`, we use the `await` keyword to pause the execution of the function until the Promise returned by `fetch()` is resolved.

Note: The async/await feature is primarily used for Promise-based async operations.

In the second `await` response.json(); when it’s done doing the conversion from JSON to JavaScript object, it was then logged to the console.

If an error occurs, since async/await allows us to handle Promises in a way that looks synchronous, we are able to use good ol’ `try/catch` blocks. The `catch` block will catch any error that is thrown from the async function.


Simply generate articles to optimize your SEO
Simply generate articles to optimize your SEO





DinoGeek offers simple articles on complex technologies

Would you like to be quoted in this article? It's very simple, contact us at dino@eiki.fr

CSS | NodeJS | DNS | DMARC | MAPI | NNTP | htaccess | PHP | HTTPS | Drupal | WEB3 | LLM | Wordpress | TLD | Domain name | IMAP | TCP | NFT | MariaDB | FTP | Zigbee | NMAP | SNMP | SEO | E-Mail | LXC | HTTP | MangoDB | SFTP | RAG | SSH | HTML | ChatGPT API | OSPF | JavaScript | Docker | OpenVZ | ChatGPT | VPS | ZIMBRA | SPF | UDP | Joomla | IPV6 | BGP | Django | Reactjs | DKIM | VMWare | RSYNC | Python | TFTP | Webdav | FAAS | Apache | IPV4 | LDAP | POP3 | SMTP

| Whispers of love (API) | Déclaration d'Amour |






Legal Notice / General Conditions of Use