async, promise调用多个接口回调

(async () => {
    await this.getInLotteryAmount()
    await this.getUser()
    await this.createNormalChatroom()
    await console.log('1-1')
})()


new Promise((resolve, reject) => {
    // this.getInLotteryAmount()
    console.log('11--')
}).then(() => {
    console.log('22--')
    this.getUser()
}).then(() => {
    console.log('33--')
    this.createNormalChatroom()
    console.log('1-1')
}).catch((err) => {
    console.log('catch--')
})

以上两种写法有问题吗?async那个回调顺序不对,promise那个直接卡住了,不走下一个then.

阅读 3.2k
2 个回答
(async () => {
    await this.getInLotteryAmount()     //1
    await this.getUser()                //2
    await this.createNormalChatroom()   //3
    await console.log('1-1')            //4
})()

上面这段代码,应该是严格按照 1》2》3》4 执行的,你说的回调顺序不对,这里看不到代码不晓得你说的什么意思

第二段代码

    new Promise((resolve, reject) => {
        // this.getInLotteryAmount()
        console.log('11--')
    }).then(() => {
        console.log('22--')
        this.getUser() // @贾克斯[jiakesi_5cb84ad20c0e5]  你需要在这做 return才能把promise 连起来
        return this.getUser()
    }).then(() => {
        console.log('33--')
        this.createNormalChatroom()
        console.log('1-1')
    }).catch((err) => {
        console.log('catch--')
    })

因为不晓得你3个函数的内部实现,以下是我模拟的示例代码,希望你有帮助

function a(){
    return new Promise((resolve, reject)=>{
        resolve({})
    })
}

function b(){
    return new Promise((resolve, reject)=>{
        resolve({})
    })
}

function c(){
    return new Promise((resolve, reject)=>{
        resolve({})
    })
}

// 模拟第一个写法
(async ()=>{
    await a();
    await c();
    await d();
})()

// 模拟第二种写法

a()
.then(data=>{
  // 这个data, 是 a 函数中的 resolve
  return b();
})
.then(data=>{
  // 这个data 是 b 函数中的 resolve
  return c();
})
.then(data=>{
  // 这个data 是 c函数 中的resolve
})
.catch(err=>{
  // 以上任何环境的 err 都会直接到这里
})

new Promise那个都没resolve 怎么走then啊
await那个回调顺序不对 没明白 哪有回调啊

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题