JS一次调多个接口的问题

比如有js要一下调用个接口a,b,c,但需求是调了a有返回值了才调b,调了b有返回值了才掉c,但调接口是异步,就是改成同步那如果调的接口太多,那then也要写可多,怎么解决这个问题。

阅读 4.4k
3 个回答

两种方法可以避免地狱回调,看例子:

const apiA = () => new Promise(resolve => resolve(1));
const apiB = () => new Promise(resolve => resolve(2));
const apiC = () => new Promise(resolve => resolve(3));

const request1 = () => {
    apiA().then(resp1 => {
        console.log(resp1)
        return apiB();
    }).then(resp2 => {
        console.log(resp2)
        return apiC();
    }).then(resp3 => {
        console.log(resp3)
    })
}

request1();
// 1 2 3

const request2 = async () => {
    console.log(await apiA());
    console.log(await apiB());
    console.log(await apiC())
}

request2();
// 1 2 3
推荐问题
宣传栏