Fetch API & Async Await

Fetch API & Async Await



const fetchJSON = (url = ``) => {
    return fetch(url,
        {
            method: "GET",
            // mode: "no-cors",
            mode: "cors",
            credentials: "same-origin",
            headers: {
                "Content-Type": "application/json; charset=utf-8",
            },
        })
        .then(res => res.json())
        .then(
            (json) => {
                return json;
            }
        )
        .catch(err => console.log(`fetch error`, err));
};

// async / await
async function getDatas(url = ``) {
    try {
        return await fetchJSON(url);
    } catch (err) {
        console.error("getDatas error:\n", err);
    }
}

转载于:https://www.cnblogs.com/xgqfrms/p/10766432.html

你可能感兴趣的:(Fetch API & Async Await)