Coinbase API响应较大且速度较慢

时间:2018-06-28 20:24:39

标签: node.js async-await coinbase-api

以下代码需要花费5到10秒钟才能解决(有5个API调用)。原样不可用。缓慢的响应是我的错,还是Coinbase API缓慢又庞大?

app.get('/buys', async (req, res) => {
    const buys = await getAllBuys()
    res.json(buys)
})

const fetchAllAccounts = () => {
    return new Promise(
        (resolve, reject) => {
            coinbase.getAccounts(null, (err, accounts) => {
                if (err) {
                    reject(err)
                }
                else{
                    resolve(accounts)
                }
            })
        }
    )
}

const fetchAllBuys = (account) => {

    return new Promise(
        (resolve, reject) => {
            account.getBuys(null, (err, buys) => {
                if (err) {
                    reject(err)
                }
                else{
                    resolve(buys)
                }
            })
        }
    )
}


const getAllBuys = async () => {
    const accounts = await fetchAllAccounts()

    let combinedBuys = []

    for (let account of accounts) {
        const buys = await fetchAllBuys(account)
        combinedBuys = [...combinedBuys, ...buys]
    }
    //console.log(combinedBuys)
    return combinedBuys
}

Response是一个数组,其中包含包含帐户信息(例如证书等)的项目。

1 个答案:

答案 0 :(得分:0)

好,那是我的代码。在上面的代码中,我等待每个请求完成,然后再发出新请求。这导致不必要的延迟。使用Promise.all方法,我们可以生成所有承诺并同时解决它们。看一下下面的重构代码。

app.get('/buys', async (req, res) => {
    console.time('[/buys]');

    const promises = await getAllBuys()
    const buys = await Promise.all(promises)
    res.json(buys)

    console.timeEnd('[/buys]');
})


const fetchAllAccounts = () => {
    return new Promise(
        (resolve, reject) => {
            coinbase.getAccounts(null, (err, accounts) => {
                if (err) {
                    reject(err)
                }
                else{
                    resolve(accounts)
                }
            })
        }
    )
}

const fetchAllBuys = (account) => {

    return new Promise(
        (resolve, reject) => {
            account.getBuys(null, (err, buys) => {
                if (err) {
                    reject(err)
                }
                else{
                    resolve(buys)
                }
            })
        }
    )
}


const getAllBuys = async () => {
    const accounts = await fetchAllAccounts()

    let promises = []

    for (let account of accounts) {
        promises.push(fetchAllBuys(account))
    }
    return promises
}

从2.5 / 3秒到0.8 / 1秒。