Promise控制A,B,C三个异步请求的顺序,并且A,B,C,存在依赖关系。

现有3个异步请求A,B,C,A的返回是B的参数,B的返回是C的参数,用Promise怎么控制A,B,C的请求顺序?我现在是这样写的,有没有更好的方式?
(补充下,这样的写法还没有考虑到某个请求reject的情况,如果考虑reject要怎么写能稍显优雅呢?)

this.A().then(res=>{
    this.B(res).then(res=>{
        this.C(res);
    })
})
已解决 悬赏分:30 - 解决时间 2022-01-16 18:17
反对 0举报 0 收藏 0

回答4

最佳
  • @

    层层依赖promise也避免不了这种回调的链式调用;你可以使用 async await,如:

    async function asyncFunc() {
        try {
            let aData = await functionA()
            let bData = await functionB(aData)
            let cData = await functionC(bData)
        } catch(err) {
            console.log(err)
        }
    }
    支持 0 反对 0 举报
    2022-01-16 13:13
  • @

    换汤不换药,但是更符合Promise的写法

    this.A().then(res=>{
        return this.B(res)
    }).then(res=>{
        return this.C(res);
    })
    支持 0 反对 0 举报
    2022-01-16 14:25
  • @

    考不考虑基于Promise的async await?

    async function requestChain() {
      try {
        const resA = await this.A();
        const resB = await this.B(resA);
        await this.C(resB)
      } catch(err) {
        // 处理reject
      }
    }
    支持 0 反对 0 举报
    2022-01-16 15:23
  • @
    async function C() {
        try {
            const result = await B()
            resolve(result)
        } catch (e) {
            console.log(e)
        }
    }
    async function B() {
        return new Promise(resolve, reject) {
            try {
                const result = await A()
                resolve(result)
            } catch (e) {
                console.log(e)
            }
        }
    }
    function A() {
        return new Promise(resolve, reject) {
            xxx
        }
    }
    支持 0 反对 0 举报
    2022-01-16 16:00