ES next & Async Await

ES next & Async Await

https://jestjs.io/docs/en/asynchronous#async-awaitjson

ES7api

new async () => {}app

const f = async () => {
    return 1;
};

 
f().then(value => console.log(value)); 
// 1
// Promise {<resolved>: undefined}

f();
// Promise {<resolved>: 1}

old async function() {}cors

async function ff() {
  return 1;
}

ff().then(alert); 
// 1
//Promise {<resolved>: undefined}

ff().then(value => console.log(value)); 
// 1
// Promise {<resolved>: undefined}


Fetch API & Async Await

practical demoasync

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);
    }
}
相關文章
相關標籤/搜索