xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

webpack & async await

webpack & async await

ES 7


// async function f() {
//   return 1;
// }

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

f().then(value => console.log(value)); // 1


https://github.com/xgqfrms/WBP/issues/3

regeneratorRuntime

Uncaught ReferenceError: regeneratorRuntime is not defined

image

https://stackoverflow.com/questions/33527653/babel-6-regeneratorruntime-is-not-defined

https://github.com/babel/babel-loader/issues/161

https://templecoding.com/blog/2016/02/17/async-await-with-es6-babel-and-typescript/

regeneratorRuntime

https://babeljs.io/docs/usage/polyfill/

Babel includes a polyfill that includes a custom regenerator runtime and core-js.

https://babeljs.io/docs/plugins/transform-regenerator/

You need to use either the Babel polyfill or the regenerator runtime so that regeneratorRuntime will be defined.

solution

https://esausilva.com/2017/07/11/uncaught-referenceerror-regeneratorruntime-is-not-defined-two-solutions/

https://babeljs.io/docs/usage/polyfill/

OR

https://babeljs.io/docs/plugins/transform-regenerator/


OK

.babelrc


{
    "presets": ["env"]
}

webpack


require("babel-polyfill");

entry: ["babel-polyfill", "./src/backend-system/select-tree"],

image


Fetch API & Async Await

practical demo

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);
    }
}

async / await & Promise error handler


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) => {
                console.log(`json`, json);
                return json;
            }
        )
        .catch(err => console.log(`fetch error`, err));
};

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


x = getDatas(`https://cdn.xgqfrms.xyz/json/fast/1.json`);


posted @ 2018-04-27 20:30  xgqfrms  阅读(397)  评论(2编辑  收藏  举报