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

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 发布文章使用:只允许注册用户才可以访问!


posted @ 2019-06-07 22:31  xgqfrms  阅读(220)  评论(3编辑  收藏  举报