Promise両目がぼんやりしてから両目が光るまで(4)-Promiseのいくつかの肝心な問題(二)
2660 ワード
promiseは複数の操作タスクをどのように連結するか
promise異常透過/透過
Promiseチェーンの割り込み
コードはgithubに同期更新されました
https://github.com/hnt815/promise
promise then() promise, then /
new Promise((resolve, reject) => {
setTimeout(() => {
console.log(" 1( )")
resolve(1)
}, 1000);
}).then(
value => {
console.log(' 1 : ', value)
console.log(' 2( )')
return 2
}
).then(
value => {
console.log(' 2 :', value)
return new Promise((resolve, reject) => {
// 3( )
setTimeout(() => {
console.log(' 3( ))')
resolve(3)
}, 1000);
})
}
).then(
value => {
console.log(' 3 : ', value)
}
)
:
1
1( )
1 : 1
2( )
2 : 2
1
3( ))
3 : 3
promise異常透過/透過
1. promise then , ,
2. ,
new Promise((resolve, reject) => {
// resolve(1)
reject(1)
}).then(
value => {
console.log('onResolved1()', value)
return 2
},
// reason => {throw reason} // reject ,
).then(
value => {
console.log('onResolved2()', value)
return 3
},
// reason => {throw reason} // reject ,
).then(
value => {
console.log('onResolved3()', value)
},
// reason => Promise.reject(reason) // reject ,
).catch(reason => {
console.log('onReejected1()', reason)
// throw reason
// return Promise.reject(reason)
}).then(
value => {
console.log('onResolved3()', value)
},
reason => {
console.log('onReejected2()', reason)
}
)
:
onReejected1() 1
onResolved3() undefined
Promiseチェーンの割り込み
promise ?
1. promise then , ,
2. : pending promise
new Promise((resolve, reject) => {
resolve(1)
}).then(
value => {
console.log('onResolved1()', value)
return new Promise(() => {}) // pending promise promise
},
).then( //
value => {
console.log('onResolved2()', value)
},
reason => {
console.log('onResolved2()', reason)
},
)
:
onResolved1() 1
コードはgithubに同期更新されました
https://github.com/hnt815/promise