使用场景
下一个调用依赖上一个调用获取的数据(结果或状态)
常规的调用方式:
比如我们在使用fetch
,或是node中的axios
,got
,node-fetch
等场景中都会得到一个promise对象,多次连续调用就会产生回调地狱
let url = 'api'
fetch(url)
.then( (res) => res.json())
.then( (data) => {
do something...
fetch(api2)
.then()
... //套娃模式
)
所有的promise对象都有then方法,我们利用promise对象的then
方法来避免回调地狱,
还是上一步的场景,但是我们不再需要在then
里传入fetch
作为回调再回调,只需要把fetch
作为返回值返回promise对象,在下面使用then
即可。这样就解决了回调地狱,使其更易理解和维护
let url = 'api'
fetch(url)
.then( (res) => res.json())
.then( (data) => {
do something...
return fetch(api1) //返回一个promise对象
)
.then( (res1) => res1.json())
.then( (data1) => {
do something...
return fetch(api2)
)
.then( (res2) => res2.json())
.then( (data2) => {
do something...
return fetch(api3)
)
...