具有多个获取请求的“退出承诺”

问题描述 投票:0回答:2

我需要合并API中的数据。我首先调用一个端点给我一个id列表,然后我为每个id做一个请求。我的目标是返回一份包含所有请求的回复的列表,但我在承诺中迷失了自己...

我的代码在NodeJS上运行。这是代码:

const fetch = require('node-fetch')

const main = (req, res) => {
  fetch('ENDPOINT_THAT_GIVES_LIST_OF_IDS')
  .then(response => response.json())
  .then(response => {
    parseIds(response)
  .then(data => {
    console.log(data)
    res.json(data)
    // I want data contains the list of responses
  })
})
.catch(error => console.error(error))
}

const getAdditionalInformations = async function(id) {
  let response = await fetch('CUSTOM_URL&q='+id, {
    method: 'GET',
  });
  response = await response.json();
  return response
}

const parseIds = (async raw_ids=> {
  let ids= []
  raw_ids.forEach(function(raw_id) {
    let informations = {
      // Object with data from the first request  
    }
    let additionalInformations = await 
getAdditionalInformations(raw_id['id'])
    let merged = {...informations, ...additionalInformations}
    ids.push(merged)
  })
  return ids
})

main()

我收到此错误:“await仅在异步函数中有效”为此行:

let additionalInformations = await getAdditionalInformations(raw_id['id'])

请帮助我承诺和异步/等待。

javascript node.js promise async-await fetch
2个回答
0
投票

你几乎就在那里,你的括号中只有一点点错误:

// notice the parentheses'
const parseIds = async (raw_ids) => {
  let ids= []
  raw_ids.forEach(function(raw_id) {
    let informations = {
      // Object with data from the first request  
    }
    let additionalInformations = await getAdditionalInformations(raw_id['id'])
    let merged = {...informations, ...additionalInformations}
    ids.push(merged)
  })
  return ids
}

-1
投票

你在forEach之后错过了一个异步

const parseIds = (async raw_ids=> {
  let ids= []
  raw_ids.forEach(async function(raw_id) {
    let informations = {
      // Object with data from the first request  
    }
    let additionalInformations = await 
getAdditionalInformations(raw_id['id'])
    let merged = {...informations, ...additionalInformations}
    ids.push(merged)
  })
  return ids
})

一个建议是:你将promises(.then())与async / await混合在一起。首选async / await更具可读性。

请注意,forEach中的getAdditionalInformation不会等到它转到数组的下一个条目之前完成。

您可以使用plain old for(var i = 0; ....

© www.soinside.com 2019 - 2024. All rights reserved.