JavaScrip OOP:ES6 Class
ES6 Class 特点 仅仅是构造函数的语法糖 不会 Hoisted First Class Citizen,即类可以被当成参数使用 Class Body 永远都只在 Strict Mode('use strict';)下执行 类表
通过 ES2017 async
/await
及 Promise Combinator 实现优雅的异步代码。
语法糖:async
/await
并没有为 JS 语言添加新特性,仅仅是为 Promise 提供了一种更易写易懂的语法。
const wait = sec =>
new Promise(resolve => setTimeout(resolve, sec * 1000));
// 通过 async/await 使用 Promise
(async () => {
await wait(1);
console.log('1秒后执行');
await wait(1);
console.log('2秒后执行');
await wait(1);
console.log('3秒后执行');
await wait(1);
console.log('4秒后执行');
})();
// Promise 原使用方式
// wait(1)
// .then(() => {
// console.log('1秒后执行');
//
// return wait(1);
// })
// .then(() => {
// console.log('2秒后执行');
//
// return wait(1);
// })
// .then(() => {
// console.log('3秒后执行');
//
// return wait(1);
// })
// .then(() => {
// console.log('4秒后执行');
//
// return wait(1);
// });
HTTP 请求报文(Request Message)和 HTTP 响应报文(Response Message)格式。
GET /posts/1 HTTP/1.1
Host: jsonplaceholder.typicode.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36
Accept-Language: en,zh;q=0.9
<BODY>
调用 fetch
函数时就会在后台立即执行 AJAX 请求。比如:
const baseUrl = 'https://jsonplaceholder.typicode.com';
// 立即执行 AJAX,并返回 Promise
const postPro = fetch(`${baseUrl}/posts/1`);
console.log(postPro); // Promise {<pending>}
AJAX 的执行与 then、catch 和 finally 无关:then
、catch
和 finally
仅仅代表在 AJAX 请求结束后,应该执行什么样的操作,而 AJAX 在调用 fetch
函数时就已经开始执行了。
const baseUrl = 'https://jsonplaceholder.typicode.com';
const request = new XMLHttpRequest();
request.open('GET', `${baseUrl}/posts/1`);
request.send();
request.addEventListener('load', function () {
const data = JSON.parse(this.responseText);
console.log(data);
});