async/promise 多次 api 调用

async/promise with multiple api calls

我有点理解回调、promises 和异步等待之间的区别,但我不太确定如何将其应用到我的问题中。

我删除了很多代码,但基本上我有一个应用程序 运行 一个端点需要执行 3 个函数(也许我需要第 4 个?)并且还发送一个“res.end()" 在 3 秒内。这 3 个功能相互依赖。我需要链接这些功能吗?我的 main() 似乎完全错误。

router.post('/', function (req, res) {

        async function deleteRule() {
            axios.delete(DeleteURL, {auth: auth, httpsAgent: agent})
            .then(response => {
                let deleteRes = response.data
                console.log(deleteRes)
            })
        }

        const list = './jsons/list.json'

        async function createRule() {
            fs.readFile(list, 'utf-8', function(err, data) {
                if (err) throw err
                var thestuff = JSON.parse(data)
            
            axios.post(CreateURL, thestuff, {auth: auth, httpsAgent: agent})
            .then(response => {
                let createRes = response.data
                console.log(createRes)
            })
        })
        }

        async function orderRule() {
            axios.put(usOrderURL, theOrder, {auth: auth, httpsAgent: agent})
            .then(response => {
                let orderRes = response.data
                console.log(orderRes)
            })
        }

        async function main() {
            const deleteListResult = await deleteRule();
            const createListResult = await createRule();
            const orderListResult = await orderRule();
        }

        main();

        // res.end must finish in 3 seconds from the initial post on the first line
        res.end() 

    })

then() 调用 return 承诺,但您不对它们执行任何操作。你应该 await 他们,或者 return 他们。

由于您将函数声明为 async,因此请在其中使用 await——这就是 async 关键字的全部要点:

async function deleteRule() {
    let response = await axios.delete(DeleteURL, {auth: auth, httpsAgent: agent});
    console.log(response.data);
    return response.data;
}

对其他两个规则函数进行类似的更改。

import fs from 'fs-extra'

const list = './jsons/list.json'

async function deleteRule() {
    const response = await axios.delete(DeleteURL, {auth: auth, httpsAgent: agent})
    const deleteRes = response.data

    console.log(deleteRes)

    return deleteRes
}
async function createRule() {
    const data = await fs.readFile(list, 'utf-8')
    const theStuff = JSON.parse(data)
    const response = await axios.post(CreateURL, theStuff, {auth: auth, httpsAgent: agent})
    const createRes = response.data
    
    console.log(createRes)

    return createRes
}
async function orderRule() {
    const response = await axios.put(usOrderURL, theOrder, {auth: auth, httpsAgent: agent})
    const orderRes = response.data
    
    console.log(orderRes)

    return orderRes
}

router.post('/', async function (req, res) {
    const deleteListResult = await deleteRule();
    const createListResult = await createRule();
    const orderListResult = await orderRule();

    // res.end must finish in 3 seconds from the initial post on the first line
    res.end() 
})