【发布时间】:2017-09-17 16:14:17
【问题描述】:
我正在尝试将新的 async/await 与对一组值的映射结合使用。 但是我有点困惑,在这种特定情况下,它前面应该有 await 关键字。
关于这个话题的信息还不是很多。
我试图简单地将 map() 和值数组放在 Axios get() 请求中,然后返回一个 then() 值,该值被添加到 map() 函数返回的数组中.
这是我现在的代码:
async function get_prices (arrayOfDates, crypto, FIAT) {
// I tried this way (return value can be found below)
let arry_of_prices = arrayOfDates.map(async function(date){
let a = await fetch_data(date, crypto, FIAT)
return a
});
// And this way (return value can be found below)
let arry_of_prices = await arrayOfDates.map(date => fetch_data(date, crypto, FIAT));
}
const fetch_data = (timestamp, crypto, FIAT) => {
axios.get(`https://min-api.cryptocompare.com/data/pricehistorical?fsym=${crypto}&tsyms=${FIAT}&ts=${timestamp}`)
.then(function (response) {
return Object.values(response.data).map(key => Object.values(key))[0][0]
})
.catch(function (error) {
console.log(error);
});
}
let arr = [1468965600, 1469052000, 1469138400,1469484000]
get_prices(arr, "BTC", "USD").then(arr => console.log(arr))
第一次尝试返回 4 个 resolved 承诺,但值是 undefined。
而第二个返回一个包含 4 个undefined 的数组。
有没有人知道如何构造它,以便map() 等到函数被解析然后将值添加到数组中?
【问题讨论】:
标签: javascript arrays asynchronous async-await