在数组值上映射时使用异步等待 [英] Using async await when mapping over an arrays values

查看:44
本文介绍了在数组值上映射时使用异步等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将新的async/await与值数组的映射结合使用.但是我有点困惑,在这种特定情况下,应该在其前面加上await关键字.

I am trying to use the new async/await in conjunction with mapping over an array of values. However I am a bit confused, which should have the await keyword infront of it, in this specific scenario.

关于此主题的信息还很多.

There isnt much information regarding this topic yet.

我试图简单地将 map()覆盖值的数组,并将其用于Axios get()请求中,然后返回一个 then()值,该值将添加到 map()函数返回的数组中.

I am trying to simply map() over and array of values, which are used in an Axios get() request, which then returns a then() value, which gets added to the array returned by the map() function.

这是我现在的代码:

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 的数组.

The first try returned 4 resolved promises, but the values were undefined. Whereas the second return an array with 4 undefined.

有人知道如何构造它,以便 map()等到函数解析后再将值添加到数组中吗?

Does anyone have an idea of how this could be structured, so that the map() waits until the function is resolved and then adds the value to the array?

推荐答案

map 对诺言一无所知,因此当对使用 async 回调时> map ,您将获得一个承诺数组,而不是值.然后,如果您想要一个在所有这些诺言都已解决后便会解决的诺言,则可以使用 Promise.all .

map doesn't know anything about promises, so when you use an async callback with map, you'll get an array of promises, not values. If you then want a promise that will resolve when all of those promises have resolved, you can use Promise.all.

但是,在您的情况下,您不需要异步函数,因为您在回调中使用了 fetch_data .您需要修改 fetch_data ,以便它从 axios.get 返回承诺(并删除 catch 处理程序):

However, in your case, you don't need an async function, since you're using fetch_data in the callback. You need to modify fetch_data so it returns the promise from axios.get (and remove the catch handler):

const fetch_data = (timestamp, crypto, FIAT) => {
  return 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]
  });
}

(这是承诺的规则之一:如果要退还承诺,则不会处理拒绝的承诺[除非您希望将其转换为不同的拒绝,或者可以将其有效地转换为分辨率].如果您退还承诺,则您执行处理拒绝.)

(This is one of the rules of promises: If you're returning the promise, you don't handle rejections from it [unless you want to convert them into different rejections, or if you can usefully convert them to resolutions instead]. If you don't return the promise, you do handle rejections.)

现在您已经有了一个承诺,因此您可以在 map 中使用它(不需要 async ):

Now you already have a promise, so you use that in the map (no need for async):

async function get_prices (arrayOfDates, crypto, FIAT) {
  let arr_of_price_promises = arrayOfDates.map(function(date){
    let a = fetch_data(date, crypto, FIAT)
    return a
  });
  return Promise.all(arr_of_price_promises);
}

注意,我从 fetch_data 前面删除了 await .我们直接返回 fetch_data 的承诺,然后等待所有这些.

Notice I removed the await from in front of fetch_data. We return fetch_data's promise directly, then wait for them all.

或带有箭头功能:

async function get_prices (arrayOfDates, crypto, FIAT) {
  let arr_of_price_promises = arrayOfDates.map(date => fetch_data(date, crypto, FIAT));
  return Promise.all(arr_of_price_promises);
}

这篇关于在数组值上映射时使用异步等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆