Is there a wait function in JavaScript

Javascript async / await

The second script with the calls to async and await is written just as linearly as the first version. The difference is in. Instead of continuing with the next line, the script waits for you await on the execution of the request and only then executes the next statement.

Asynchronous with fetch

fetch is like setTimeout inherently asynchronous.

const response = fetch ("https://api.com/values"); const json = response.json (); console.log (json);

Naturally, this doesn't work either, because every request via the network takes time, regardless of whether it accesses an external resource or the same web space itself.

So we use then.

fetch ("https://api.com/values") .then (response => response.json ()) .then (json => console.log (json));

It works, but doesn't read as intuitively as the first version. Today, await / async is available for this in the modern browser. async / await is easier to read and understand than script code with promises. Generate it async and await under the candy promisses.

async as part of the declaration of a function indicates that the code should be executed asynchronously. await before a statement returns a promise that the function will stop and wait for the result before continuing.

const response = await fetch ("https://api.com/values"); const json = await response.json (); console.log (json);

await before the fetch causes the fetch request to be executed before the next line is attacked.

A more general approach with try - catch:

{"list": [{"title": "A brief history of almost everything", "author": "Bryson, Bill", "year": "2003"}, {"title": "Accidental Empires", " author ":" Cringely, Robert X. "," year ":" 1992 "}, {" title ":" rich and poor "," author ":" Diamond, Jared "," year ":" 1997 "}, {"title": "Enchanting April", "author": "Elisabeth v. Armin", "year": "1992"}]} const getBooks = async (num) => {try {let response = await fetch (" file.json "); let json = await response.json (); let list = json.list; console.log (list [num] .autor)} catch (e) {console.log ("Data was not loaded", e); }} getBooks (2);

Asynchronous anonymous functions

We can make an anonymous function of this, instantly thanks to the keywords async and await without the call getBooks (2) is performed.

(async (num) => {try {let response = await fetch ("file.json"); let json = await response.json (); let list = json.list; console.log (list [num] .autor )} catch (e) {console.log ("Data was not loaded", e);}}) (2);

Now let's get the keywords async and await delete from the script, there would be an error message in the console.

Data was not loaded TypeError: response.json is not a function. (In 'response.json ()', 'response.json' is undefined) (anonymous function)

response.json would be called before the file was loaded.

External sources and more