Promise入门之:让函数返回一个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")
运行结果:
$ 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")
运行结果:
$ node test.js
111
222
then1: aaa
then2: undefined
then3: bbb
eeee1: ccc
eeee2
注意在函数foo里面"then3"的位置,需要返回Promise.reject(),然后这个reject被"eeee1"处的catch捕获,然后这里必须再返回一个Promise.reject()到函数外面;如不然,相当于foo函数内部消化掉了"then3"位置的exception,导致在函数外部"eeee2"位置并不能捕获异常,因为此处会认为就没有异常发生。