ES Next & Arrow function & Promise & Iterator & Generator yield & Async Await
ES Next & Arrow function & Promise & Iterator & Generator yield & 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);
}
}
// demo
getDatas(`https://cdn.xgqfrms.xyz/json/ssr/posts.json`);
Iterator & Generator yield
迭代器,生成器
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Iterators_and_Generators
function* idMaker(ids = []) {
let len = ids.length;
if(len) {
for(let i = 0; i < len; i++) {
yield i;
}
} else {
yield undefined;
}
}
let gen = idMaker([0, 1, 2]);
gen.next();
// {value: 0, done: false}
gen.next();
// {value: 1, done: false}
gen.next();
// {value: 2, done: false}
gen.next();
// {value: undefined, done: true}
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/10989410.html
未经授权禁止转载,违者必究!