Reputation: 1967
I have this function that returns a Promise which resolves to an object that is later inserted into db.
lastPrice (crypto) {
return axios.get('https://www.bitmex.com/api/v1/instrument/active').then(res => {
return _.map(_.filter(res.data, instrument => isMatch(instrument, crypto)), y => {
return { exchange: getExchangeName(y.symbol), order: getOrder(y.symbol), crypto, lastPrice: getLastPrice(y) }
})
}).catch((e) => { Promise.resolve() })
}
isMatch, getExchangeName, getOrder and getLastPrice used to be sync functions. Now I need getLastPrice to be async.
function getLastPrice (instrument) {
const regex = /^(ETH)[FNGQHUJVKXZM]\d{2}$/
let regexResult = regex.exec(instrument.symbol) || []
if (regexResult.length > 0) {
const app = require('../../app')
return app.service('exchanges').find({
query: {
exchange: 'BMEXperp',
crypto: 'ETH'
}
}).then(res => {
if (res.total === 0) {
return 0
}
return res.data[0].lastPrice * instrument.lastPrice
})
} else {
return instrument.lastPrice
}
I need to keep the same functionality but with an async lastPrice(crypto). Basically getLastPrice should still return a Promise that resolves to an object with no promises in it.
My idea is not to modify the function that calls lastPrice, which is this one:
exchange.lastPrice(crypto).then(res => {
res = res || []
res.forEach(element => {
exchangesService.create(element)
})
})
Upvotes: 2
Views: 1114
Reputation: 5217
Missing part is Promise.all
.
If you can use async/await then I think something like this is what you want:
lastPrice (crypto) {
return axios.get('https://www.bitmex.com/api/v1/instrument/active')
.then(res => {
const filteredList = _.filter(res.data, instrument => isMatch(instrument, crypto))
const promises = _.map(filteredList, async (y) => {
return {
exchange: getExchangeName(y.symbol),
order: getOrder(y.symbol),
crypto,
lastPrice: await getLastPrice(y),
}
})
return Promise.all(promises)
}).catch((e) => { Promise.resolve() })
}
Upvotes: 3