一. 聲明變量的方法:
let 用來聲明變量。
1.屬于塊級作用域,只在let命令所在的代碼塊內(nèi)有效;
2.同時聲明兩個變量,會報錯;
3.不可做變量提升;
4.let聲明的變量不屬于頂層對象屬性,全局變量將逐步與頂層對象的屬性脫鉤。
const 用來聲明常量。
1.初始化的時候必須有值;
2.不能重新賦值,重新賦值后會報錯;
3.對于const聲明的是數(shù)組或?qū)ο髸r,可更改屬性,不可重新賦值;
import
class
//例題1:
function f1() {
let n = 5;
if (true) {
let n = 10;
}
console.log(n);
}
//例題2:
function f() { console.log('I am outside!'); }
(function () {
var f = undefined;
if (false) {
function f() { console.log('I am inside!'); }
}
f();
}());
//例題3
const a = [];
a.push('Hello');
a.length = 0;
a = ['Dave'];
//例題4
var a = 1;
window.a
let b = 1;
window.b
二. 變量的解構(gòu)賦值
數(shù)組的解構(gòu)賦值 let [a, b, c] = [1, 2, 3];
1.基本用法,數(shù)組的元素是按次序排列的,變量的取值由它的位置決定;
let [foo, [[bar], baz]] = [1, [[2], 3]];
foo
bar
baz
let [ , , third] = ["foo", "bar", "baz"];
third
let [x, , y] = [1, 2, 3];
x
y
let [head, ...tail] = [1, 2, 3, 4];
head
tail
let [x, y, ...z] = ['a'];
x
y
z
let [foo] = [];
let [bar, foo] = [1];
foo
foo
let [x, y] = [1, 2, 3];
x
y
let [a, [b], d] = [1, [2, 3], 4];
a
b
d
2.解構(gòu)賦值允許指定默認(rèn)值,默認(rèn)值是一個表達(dá)式,那么這個表達(dá)式是惰性求值的;
let [x, y = 'b'] = ['a'];
x
y
let [x, y = 'b'] = ['a', undefined];
x
y
function f() {
console.log('aaa');
}
let [x = f()] = [1];
let [x = 1, y = x] = [];
x
y
let [x = 1, y = x] = [2];
x
y
let [x = 1, y = x] = [1, 2];
x
y
let [x = y, y = 1] = [];
x
y
對象的解構(gòu)賦值
1.對象的屬性沒有次序,變量必須與屬性同名,才能取到正確的值。
let { foo, bar } = { foo: "aaa", bar: "bbb" };
bar
foo
let { baz } = { foo: "aaa", bar: "bbb" };
baz
2.變量名與屬性名不一致的寫法
let obj = { first: 'hello', last: 'world' };
let { first: f, last: l } = obj;
f
l
let { foo: baz } = { foo: "aaa", bar: "bbb" };
baz
foo
字符串的解構(gòu)賦值
字符串也可以解構(gòu)賦值。這是因?yàn)榇藭r,字符串被轉(zhuǎn)換成了一個類似數(shù)組的對象。
類似數(shù)組的對象都有一個length屬性,因此還可以對這個屬性解構(gòu)賦值。
const [a, b, c, d, e] = 'hello';
a
b
c
d
e
let {length : len} = 'hello';
len
三.Promise對象
const promise = new Promise(function(resolve, reject) {
// ... some code
if (/* 異步操作成功 */){
resolve(value);
} else {
reject(error);
}
});
//Promise實(shí)例生成以后,可以用then方法分別指定resolved狀態(tài)和rejected狀態(tài)的回調(diào)函數(shù)。
promise.then(function(value) {
// success
}, function(error) {
// failure
});
1.Promise對象是一個構(gòu)造函數(shù),用來生成Promise實(shí)例。
2.Promise是實(shí)現(xiàn)異步編程的一種解決方案
3.Promise構(gòu)造函數(shù)接受一個函數(shù)作為參數(shù),該函數(shù)的兩個參數(shù)分別是resolve和reject。 resolve的作用是從未完成變?yōu)槌晒Γ磸?pending 變?yōu)?resolved),reject的作用是從未完成變?yōu)槭。磸?pending 變?yōu)?rejected)
//例題:用Promise對象實(shí)現(xiàn)的 Ajax 操作的例子
const getJSON = function(url) {
const promise = new Promise(function(resolve, reject){
const handler = function() {
if (this.readyState !== 4) {
return;
}
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error(this.statusText));
}
};
const client = new XMLHttpRequest();
client.open("GET", url);
client.onreadystatechange = handler;
client.responseType = "json";
client.setRequestHeader("Accept", "application/json");
client.send();
});
return promise;
};
getJSON("/posts.json").then(function(json) {
console.log('Contents: ' + json);
}, function(error) {
console.error('出錯了', error);
});
4.調(diào)用resolve或reject并不會終結(jié) Promise 的參數(shù)函數(shù)的執(zhí)行。
new Promise((resolve, reject) => {
resolve(1);
console.log(2);
}).then(r => {
console.log(r);
});
5.Promise.prototype.then()
promise實(shí)例具有then方法,也就是說,then方法是定義在原型對象Promise.prototype上的。then方法返回的是一個新的Promise實(shí)例(注意,不是原來那個Promise實(shí)例)。因此可以采用鏈?zhǔn)綄懛ǎ磘hen方法后面再調(diào)用另一個then方法(第一個回調(diào)函數(shù)完成以后,會將返回結(jié)果作為參數(shù),傳入第二個回調(diào)函數(shù))。
getJSON("/post/1.json").then(function(post) {
return getJSON(post.commentURL);
}).then(function funcA(comments) {
console.log("resolved: ", comments);
}, function funcB(err){
console.log("rejected: ", err);
});
//箭頭函數(shù)寫更為簡單
getJSON("/post/1.json").then(
post => getJSON(post.commentURL)
).then(
comments => console.log("resolved: ", comments),
err => console.log("rejected: ", err)
);
6.Promise.prototype.catch()
如果 Promise 狀態(tài)已經(jīng)變成resolved,再拋出錯誤是無效的。
const promise = new Promise(function(resolve, reject) {
resolve('ok');
throw new Error('test');
});
promise
.then(function(value) { console.log(value) })
.catch(function(error) { console.log(error) });
不要在.then方法里面定義 Reject 狀態(tài)的回調(diào)函數(shù)(即then的第二個參數(shù)),總是使用catch方法。.catch可以捕獲前面then方法執(zhí)行中的錯誤
// bad
promise
.then(function(data) {
// success
}, function(err) {
// error
});
// good
promise
.then(function(data) { //cb
// success
})
.catch(function(err) {
//
Promise 內(nèi)部的錯誤不會影響到 Promise 外部的代碼。
const someAsyncThing = function() {
return new Promise(function(resolve, reject) {
// 下面一行會報錯,因?yàn)閤沒有聲明
resolve(x + 2);
});
};
someAsyncThing().then(function() {
console.log('everything is great');
});
setTimeout(() => { console.log(123) }, 2000)
Promise 對象建議后面要跟catch方法,這樣可以處理 Promise 內(nèi)部發(fā)生的錯誤。catch方法返回的還是一個 Promise 對象,因此后面還可以接著調(diào)用then方法。
const someAsyncThing = function() {
return new Promise(function(resolve, reject) {
// 下面一行會報錯,因?yàn)閤沒有聲明
resolve(x + 2);
});
};
someAsyncThing()
.catch(function(error) {
console.log('oh no', error);
})
.then(function() {
console.log('carry on');
});
7.Promise.prototype.finally()
finally方法用于指定不管 Promise 對象最后狀態(tài)如何,都會執(zhí)行的操作。該方法是 ES2018 引入標(biāo)準(zhǔn)的。
promise
.then(result => {···})
.catch(error => {···})
.finally(() => {···});
8.Promise.all()
Promise.all方法用于將多個 Promise 實(shí)例,包裝成一個新的 Promise 實(shí)例。
const p = Promise.all([p1, p2, p3]);
9.總結(jié):
優(yōu)點(diǎn):Promise 的寫法是回調(diào)函數(shù)的改進(jìn),使用then方法以后,異步任務(wù)的兩段執(zhí)行看得更清楚了。then將原來異步函數(shù)的嵌套關(guān)系轉(zhuǎn)變?yōu)殒準(zhǔn)讲襟E
缺點(diǎn):Promise 的最大問題是代碼冗余,原來的任務(wù)被Promise 包裝了一下,不管什么操作,一眼看去都是一堆 then,原來的語義變得很不清楚.