Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
481 views
in Technique[技术] by (71.8m points)

请问下js里面async这样用可以实现异步串行的功能吗?

async function handleData () {
    const res1= await getData1()
           if (res1.code === 'ok') {
                const res2 = await getData2()
                    if (res2.code === 'ok') {
                        const res3 = await getData3()
                        .....
                        ......
                    }
           }
   }

getData1 2 3都是调用api获取数据的方法,大概功能就是根据res1的数据去给下一个接口传参数,获得了数据以后接着请求下一个接口,就是一个根据一级目录或二级目录获取三级目录的方法。请问下我这么写能实现吗?如果不行请问下该怎么实现异步串行呀?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

这样写应该是可以实现异步串行的
不知道你是不是我这样想的:
声明三个函数,都返回一个promise出来,例如:

function getData1(data) {
    return new Promise((resolve, reject) => {
        // 这里调用api,当res1.code === 'ok'时候 抛出resolve
        API.getData1(data).then(res => {
            if (res1.code === 'ok') {
                resolve(res)
            } else {
                reject()
            }
        })
    })
}

然后在async函数中使用

async function handleData () {
    let res1, res2, res3
    res1= await getData1(data)
    res1 && (res2 = await getData2(res1.data))
    res2 && (res3 = await getData3(res2.data))
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...