Promise入門之:讓函數(shù)返回一個Promise對象
1:返回一個resolve
function foo() {
return Promise.resolve('aaa')
.then(data => { console.log("then1: ", data); })
.then(data => { console.log("then2: ", data); return 'bbb'; })
.then(data => { console.log("then3: ", data); return Promise.resolve('ccc'); })
.catch(err => { console.log("eee"); return Promise.reject('eee'); });
}
console.log("111")
foo()
.then(data => { console.log("333: ", data); })
.catch(err => { console.log("eee"); return 'ggg'});
console.log("222")
運行結(jié)果:
$ node test.js
111
222
then1: aaa
then2: undefined
then3: bbb
333: ccc
2: 返回一個reject
function foo() {
return Promise.resolve('aaa')
.then(data => { console.log("then1: ", data); })
.then(data => { console.log("then2: ", data); return 'bbb'; })
.then(data => { console.log("then3: ", data); return Promise.reject('ccc'); })
.catch(err => { console.log("eeee1: ", err); return Promise.reject('ddd'); });
}
console.log("111")
foo()
.then(data => { console.log("333: ", data); })
.catch(err => { console.log("eeee2"); return 'ggg'});
console.log("222")
運行結(jié)果:
$ node test.js
111
222
then1: aaa
then2: undefined
then3: bbb
eeee1: ccc
eeee2
注意在函數(shù)foo里面"then3"的位置墨缘,需要返回Promise.reject()歼秽,然后這個reject被"eeee1"處的catch捕獲渠欺,然后這里必須再返回一個Promise.reject()到函數(shù)外面九默;如不然,相當(dāng)于foo函數(shù)內(nèi)部消化掉了"then3"位置的exception尝盼,導(dǎo)致在函數(shù)外部"eeee2"位置并不能捕獲異常懊纳,因為此處會認(rèn)為就沒有異常發(fā)生掰读。