在开发过程中,遇到嵌套调用接口的时候,就是下一个接口访问参数需要上一个接口返回值提供,这个时候可以用promise来实现异步请求
废话不多说,直接上代码
// 首先定义一个promise 构造函数
const p = new Promise((resolve, reject) => {
pubplaPage({ limit: 100, page: 1, publishState: "2" })
.then((res: any) => {
console.log(1111111)
resolve(res.data.records)//这里是成功时调用,默认调用p.then的第一个函数
})
})
p.then(value => {//这里的value收到的是上面resolve传来的参数
console.log(222,value)
return new Promise((resolve, reject) => {
briefsReq({ limit: 10, page: 1 })
.then((res: any) => {
console.log(222222222222)
resolve(res.data.records)
})
})
}).then(value => {//这里的value收到的是上面resolve传来的参数
console.log(333,value)
return new Promise((resolve, reject) => {
pubplaPage({ limit: 10, page: 1 })
.then((res: any) => {
console.log(333333333)
resolve(res.data.records)
})
})
})
还有一个异步请求的方法 async await组合
//async和await 一定是搭配使用的,
// await定义的函数返回类型必须是promise
// 这里用到的2个接口都是axios封装好的,刚好axios的请求返回的就是promise对象
async function main () {
let a = await pubplaPage({ limit: 10, page: 1 })
let b = await briefsReq({ limit: a.total, page: 1 })
}