我具有此函数,该函数返回Promise,该Promise解析为以后插入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和getLastPrice曾经是同步功能。现在,我需要getLastPrice进行异步处理。
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
}
我需要保留相同的功能,但要使用lastPrice(crypto)异步。基本上,getLastPrice仍应返回一个Promise,该Promise可以解析为其中没有任何承诺的对象。
我的想法是不修改调用lastPrice的函数,即该函数:
exchange.lastPrice(crypto).then(res => {
res = res || []
res.forEach(element => {
exchangesService.create(element)
})
})
答案 0 :(得分:3)
缺少的部分是Promise.all
。
如果您可以使用async / await,那么我想您想要的是这样的
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() })
}