Skip to content

Instantly share code, notes, and snippets.

@xgqfrms-GitHub
Last active June 10, 2017 14:00
Show Gist options
  • Save xgqfrms-GitHub/b44ba9049575654e36e3032c58576931 to your computer and use it in GitHub Desktop.
Save xgqfrms-GitHub/b44ba9049575654e36e3032c58576931 to your computer and use it in GitHub Desktop.
fetch-json & Arrow functions

fetch & json & Arrow functions

http://www.betterpixels.co.uk/projects/2015/05/09/mock-up-your-rest-api-with-json-server/

fetch('http://localhost:3000/tasks/')
  .then(function(response) {
    return response.json()
  }).then(function(json) {
    console.log('parsed json: ', json)
  }).catch(function(ex) {
    console.log('parsing failed: ', ex)
  });
fetch('http://localhost:3000/tasks/', {
  method: 'post',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
       "title":   "Add a blogpost about Angular2",
       "dueDate": "2015-05-23T18:25:43.511Z",
       "done": false
   })
}).then(function(response) {
      return response.json()
    }).then(function(json) {
      console.log('parsed json: ', json)
    }).catch(function(ex) {
      console.log('parsing failed: ', ex)
    });
@xgqfrms-GitHub
Copy link
Author

xgqfrms-GitHub commented May 16, 2017

https://gist.github.com/xgqfrms-GitHub/88a8ea67005f76146a1a99f7737d80df

HAR 文件 (.har)

HAR(HTTP 归档) 是多种 http 会话工具用来导出所记录数据的一种文件格式。
这种格式基本上是JSON 对象,并具有特定的字段分布。
在任何情况下,都请注意并非所有字段都是必填字段。
很多时候,部分信息不会保存到文件中。

HAR 分析器

https://toolbox.googleapps.com/apps/har_analyzer/

https://toolbox.googleapps.com/apps/browserinfo/

G Suite 工具箱

https://toolbox.googleapps.com/apps/main/

日志分析器

https://toolbox.googleapps.com/apps/loganalyzer/

日志分析器 2

https://toolbox.googleapps.com/apps/loggershark/

HAR Viewer

http://www.softwareishard.com/blog/har-viewer/

Yarn & Google’s HAR Analyzer / HAR Viewer

https://yarnpkg.com/zh-Hans/docs/cli/install

$ yarn install --har

从安装期间的所有网络请求输出一个 HTTP archive。
HAR 文件通常用于排查网络性能,并能用 Google’s HAR AnalyzerHAR Viewer 这样的工具分析。

@xgqfrms-GitHub
Copy link
Author

xgqfrms-GitHub commented May 16, 2017

RESTful & Rest parameters

http://www.ruanyifeng.com/blog/2011/09/restful.html

https://www.zhihu.com/question/28557115

Arrow_functions

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions

一个箭头函数表达式的语法比一个函数表达式更短,并且不绑定自己的 this,arguments,super或 new.target。
这些函数表达式最适合用于非方法函数,并且它们不能用作构造函数。

基础语法

(param1, param2, , paramN) => { statements }

(param1, param2, , paramN) => expression

// 等价于:  => { return expression; } 

// 如果只有一个参数,圆括号是可选的:

(singleParam) => { statements }

singleParam => { statements }

// 无参数 或者 多参数的箭头函数需要使用圆括号或者下划线:

() => { statements } 

_ => { statements }

高级语法

//对体进行括号, 返回一个对象字面表达式

params => ({foo: bar})

// 支持 其余/休息 参数 Rest parameters 和默认参数 default parameters:

(param1, param2, ...rest) => { statements }

(param1 = defaultValue1, param2, , paramN = defaultValueN) => { statements }

// 也支持参数列表中的解构赋值 Destructuring

let f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;

f();  

// 6

@xgqfrms-GitHub
Copy link
Author

@xgqfrms-GitHub
Copy link
Author

asscii emoji

<!--
 ━━━━━━神兽出没━━━━━━
     ┏┓   ┏┓
    ┏┛┻━━━┛┻┓
    ┃       ┃
    ┃   ━   ┃
    ┃ ┳┛ ┗┳ ┃
    ┃       ┃
    ┃   ┻   ┃
    ┃       ┃
    ┗━┓   ┏━┛Code is far away from bug with the animal protecting
      ┃   ┃    神兽保佑,代码无bug
      ┃   ┃
      ┃   ┗━━━┓
      ┃       ┣┓
      ┃       ┏┛
      ┗┓┓┏━┳┓┏┛
       ┃┫┫ ┃┫┫
       ┗┻┛ ┗┻┛
  ━━━━━━感觉萌萌哒━━━━━━
-->

@xgqfrms-GitHub
Copy link
Author

fetch-json

@xgqfrms-GitHub
Copy link
Author

xgqfrms-GitHub commented May 16, 2017

https://hacks.mozilla.org/2015/06/es6-in-depth-arrow-functions/

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions

/**
 * copyright 2017 xgqfrms
 * 2017.05.16
 * fetch-api
 * es6/es7
 */



/*

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/async_function

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/await

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions



*/

let x1 = (param1, param2, ...) => {
    console.log(`%c {statements}`, `color: red;`);
}
// Uncaught SyntaxError: Unexpected token )

x1 = (param1, ..., paramn) => {
    console.log(`%c {statements}`, `color: red;`);
}
// Uncaught SyntaxError: Unexpected token ,

x1 = (param1, ... , paramn) => {
    console.log(`%c {statements}`, `color: red;`);
}
// Uncaught SyntaxError: Unexpected token ,


x1 = (param1, ...rest , paramn) => {
    console.log(`%c {statements}`, `color: red;`);
}
// Uncaught SyntaxError: Rest parameter must be last formal parameter

x1 = (param1, paramn, ...rest ) => {
    console.log(`%c {statements}`, `color: red;`);
}

x1 = (param1, paramn) => {
    console.log(`%c {statements}`, `color: red;`);
}

x1();

// {statements}

http://www.betterpixels.co.uk/projects/2015/05/09/mock-up-your-rest-api-with-json-server/

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/await

https://blog.risingstack.com/node-js-async-best-practices-avoiding-callback-hell-node-js-at-scale/

@xgqfrms-GitHub
Copy link
Author

default rest
documentfragment

@xgqfrms-GitHub
Copy link
Author

Node.js异步操作:async.js,promises,generator和async函数。

https://blog.risingstack.com/node-js-async-best-practices-avoiding-callback-hell-node-js-at-scale/

@xgqfrms-GitHub
Copy link
Author

Arrow functions 解析顺序

在箭头函数中的箭头不是操作符(或者运算符,就像'+ -'那些), 但是箭头函数有特殊的解析规则就是:
相比普通的函数,受操作符的优先级影响。

let callback;

callback = callback || function() {};
 // ok

callback = callback || () => {};     
 // SyntaxError:非法箭头函数属性

callback = callback || (() => {});   
 // ok

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions#解析顺序

@xgqfrms-GitHub
Copy link
Author

news api & fetch

https://gist.github.com/xgqfrms-GitHub/d8afbd6484cf10da3603c6f51d6d4907

get-head nobody

fetch('https://newsapi.org/v1/articles?source=the-next-web&sortBy=latest',{
    method: 'get',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'X-Api-Key': `0987b00e542141369049e647701b65d9`
    }
})
.then(function(response) {
    return response.json()
}).then(function(json) {
    console.log('parsed json: ', json)
}).catch(function(error) {
    console.log('parsing failed: ', error)
});



fetch('https://newsapi.org/v1/articles?source=the-next-web&sortBy=latest&apiKey=0987b00e542141369049e647701b65d9')
.then(function(response) {
    return response.json()
}).then(function(json) {
    console.log('parsed json: ', json)
}).catch(function(error) {
    console.log('parsing failed: ', error)
});

@xgqfrms-GitHub
Copy link
Author

HTTP Headers

https://gist.github.com/xgqfrms-GitHub/636260e8332f0fe4f530fe040ffd3741

// https://api.mlab.com/api/1/databases/node-mongodb/collections/test?apiKey=pa4Yku0O7y6CHLqKwDGlLKSfkdPfQprR
const url = `https://api.mlab.com/api/1/databases/node-mongodb/collections/test?apiKey=pa4Yku0O7y6CHLqKwDGlLKSfkdPfQprR`;

fetch(url, {
    method: "PUT",
    body: JSON.stringify({}),
    headers: {
        'Accept': 'application/json',
        'Access-Control-Request-Method': 'PUT',
        'Content-Type': 'application/json'
    },
    credentials: "same-origin"
}).then(function(response) {
    response.status; //=> number 100–599
    response.statusText; //=> String
    response.headers; //=> Headers
    response.url; //=> String

    return response.text()
}, function(error) {
    error.message; //=> String
})

@xgqfrms-GitHub
Copy link
Author

@xgqfrms-GitHub
Copy link
Author

(() => {
    fetch('https://cdn.xgqfrms.xyz/json/xgqfrms.json', {
        method: 'get',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        }
    }).then((response) => {
            console.log('parsed response: ', response);
            return response.json();
    }).then((json) => {
            console.log('parsed json: ', json);
            populateWithCourses(data.courses.completed);
            populateWithCourses(data.courses.in_progress);
            hide();
    }).catch((error) => {
          console.log('parsing failed: ', error);
          setTimeout(() =>{
              alert(`faild to load data!`);
              // redirect to 
              this.window.location = `https://learning.xgqfrms.xyz`;
          }, 3000);
    });
    populateWithCourses = (courses) => {
        const $badges = $('#badges');
        console.log(`courses`, courses);
        courses.forEach(function(course) {
            $div = $('<div />', {
                'class': 'course'
            }).appendTo($badges);

            $('<h3 />', {
                text: course.title
            }).appendTo($div);

            $('<img />', {
                src: course.badge
            }).appendTo($div);

            $('<a />', {
                'class': 'btn btn-primary',
                target: '_blank',
                href: course.url,
                text: 'See Course'
            }).appendTo($div);
        });
    }
    const hide = () => {
        const hideLoad = document.getElementById('hideLoad');
        let state = "showTure";
        if (state === "showTure") {
            hideLoad.classList.remove('showTure');
            hideLoad.classList.add("hidenTure");
            console.log(`state = "showTure"`);
            hideLoad.style.display = "none";
        } else {
            console.log(`state = "hidenTure"`);
        }
    }
})();

https://learning.xgqfrms.xyz/JavaScript/Ajax/Ajax-Portfolio.html

@xgqfrms-GitHub
Copy link
Author

@xgqfrms-GitHub
Copy link
Author

parsed json

json = response.json();

fetch(`https://api.github.com/users/xgqfrms/repos`)
.then(function(response) {
    let json = response.json();
    console.log(`response = ${json}`);
    return json;
})
.then(function(json) {
    console.log('parsed json: ', json)
});




fetch(`https://api.github.com/users/xgqfrms/repos`, {
    method: 'get',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    }
})
.then(function(response) {
    return response.json();
    // json() ???
})
.then(function(json) {
    console.log('parsed json: ', json)
})
.catch(function(error) {
    console.log('parsing failed: ', error)
});

@xgqfrms-GitHub
Copy link
Author

xgqfrms-GitHub commented Jun 10, 2017

 fetch(`https://api.github.com/users/xgqfrms/repos`)
.then(function(response) {
    let json = response.json();
    console.log(`response = ${json}`);
    return json;
})
.then(function(json) {
    console.log('parsed json: ', json);
    console.log('parsed json: ', json[0]);
    console.log('parsed json: ', json[1].name);
});



 fetch(`https://api.github.com/users/xgqfrms/repos`)
.then(function(response) {
    let json = response.json();
    console.log(`response = ${json}`);
    return json;
})
.then(function(json) {
    console.log('parsed json: ', json);
    console.log('parsed json: ', json[0].owner);
    console.log('parsed json: ', json[1].name);
});

@xgqfrms-GitHub
Copy link
Author

fetch(`https://api.github.com/users/xgqfrms/repos`, {
    method: 'get',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    }
})
.then(function(response) {
    return response.json();
    // json() ???
})
.then(function(json) {
    console.log('parsed json: ', json);
    console.log('parsed json: ', json[0]);
    console.log('parsed json: ', json[1].name);
})
.catch(function(error) {
    console.log('parsing failed: ', error);
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment