简体   繁体   中英

How do I async await multiple promises in parallel? [Syntax Error: await is a reserved word]

I am querying some data from airtable which is basically a database of books and related authors. Each book record has an authorId field which I have to query separately to fetch related author data.

Here is how I get all books first:

let books = await axios.get("https://api.airtable.com/v0/appGI25cdNsGR2Igq/Books?&view=Main%20View")
let authorIds = books.data.records.map( ( book) => book.fields.Author[0] )

This works and I get these author ids:

[ 'recNLaQrmpQzfkOZ1',
  'recmDfVxRp01x85F9',
  'recKQqdJ9a2pHnF2z',
  'recKMiDhdCUxfdPSY',
  'rec67WoUDFjFMrw44' ]

Now I want to send this data to a getAuthors function like this:

const getAuthors = async (authorIds) => {
  authorIds.map( id => await Promise.all([
    return axios.get(`https://api.airtable.com/v0/appGI25cdNsGR2Igq/Authors/${id}`
  ])))
}

This function is supposed to get me my related author data but instead I get an error:

Syntax Error: await is a reserved word

...on this line: authorIds.map( id => await Promise.all([...

What am I doing wrong and is there a way to fix this?

You have placed the await in the map callback function, not in the one that is declared as async . You'll want to use

async function getAuthors(authorIds) {
  await Promise.all(authorIds.map(id =>
    axios.get(`https://api.airtable.com/v0/appGI25cdNsGR2Igq/Authors/${id}`)
  ));
}

Though probably better replace the await by return .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM