Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

fetch API

We can print some FETCH Web API and observe that the return is a Promise, so for fetch we can call the FETCH API either Promise or async/await.

console.log(fetch("https://jsonplaceholder.typicode.com/todos/1")) #Promise {<pending>}
Copy the code

Here the fetch return value is output to see its structure.

fetch("https://jsonplaceholder.typicode.com/todos/1")
.then(res= > console.log(res))
Copy the code

Return a Response object, where OK indicates that the request is returned correctly, status indicates the status of the HTTP request, and then call its JSON method to obtain data.

Promise way to fetch

fetch(url)
    .then(res= > res.json())
    .then(data= > console.log(data))
    .catch(error= > console.log(error))
Copy the code

Fetch is a browser that provides a Web API, returns a Promise, fetches the object returned from the server using the then method, calls the JSON () method that returns the object, retrieves the data in JSON format, and returns it. Note that this is also a Promise object.

Async/await the fetch method


const loadData = async() = > {const url = "https://jsonplaceholder.typicode.com/todos/1"

    const res = await fetch(url);

    const data = await res.json()

    console.log(data)
}

loadData()
Copy the code

We can rewrite the code using async/await, we need to add async to the function and then we can add await to the asynchronous function inside the method so that the function looks like it is being asynchronously programmed, inside the async function it will be executed from the top down, line by line, A function that encounters an await mark will wait for the asynchronous operation to complete and return the value and proceed.

const loadData = async() = > {try {

        const url = "https://hehejsonplaceholder.typicode.com/todos/1"

        const res = await fetch(url);

        const data = await res.json()

        console.log(data)

    } catch (error) {

        console.log(error)

    }
}
Copy the code

The above code does not handle errors, but instead uses try/catch to catch errors.

const loadData = async() = > {try {

        const url = "https://jsonplaceholder.typicode.com/todos/1"
        const res = await fetch(url);

        console.log(res.ok)

        const data = await res.json()

        return data

    } catch (error) {

        console.log(error)

    }

}

loadData().then(((data) = >console.log(data)))
Copy the code

top-level await

It is also possible to use top-level async to call await functions outside the async method to get the return value.

const data = await loadData()
console.log(data)
Copy the code

Doing so will cause the browser to throw an exception

Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules
Copy the code

For now, we can do this with a trick,

(async() = > {const data = await loadData();
    console.log(data)

})()
Copy the code

Promise. All parallel

We use ayNC /await mode to request multiple data, but these asynchronous requests are made one by one and need to wait for the end of the previous asynchronous request before the next one, but promise. All will make a set of promises to make parallel requests and then return data.

const loadData = async() = > {try {

        const url1 = "https://jsonplaceholder.typicode.com/todos/1"

        const url2 = "https://jsonplaceholder.typicode.com/todos/2"

        const url3 = "https://jsonplaceholder.typicode.com/todos/3"


        const res1 =  await fetch(url1);

        const data1 = await res1.json();

        console.log(data1);

        const res2 =  await fetch(url2);

        const data2 = await res2.json();

        console.log(data2);

        const res3 =  await fetch(url3);

        const data3 = await res3.json();

        console.log(data3);


        // return data

    } catch (error) {

        console.log(error)

    }

}
loadData()
Copy the code

Optimize the code above with Promise All.


const loadData = async() = > {try {

const url1 = "https://jsonplaceholder.typicode.com/todos/1"

const url2 = "https://jsonplaceholder.typicode.com/todos/2"

const url3 = "https://jsonplaceholder.typicode.com/todos/3"

const results = await Promise.all([

fetch(url1),

fetch(url2),

fetch(url3),

])

const dataPromise = results.map(result= >result.json())

const data = Promise.all(dataPromise)

return data

}catch(err){

console.log(err)

}

}

\


(async() = > {const data = await loadData();

console.log(data)

})()
Copy the code