带有多个提取请求的“退出承诺”

时间:2019-04-28 02:49:58

标签: javascript node.js promise async-await fetch

我需要合并来自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'])

请帮助我实现诺言和异步/等待。

2 个答案:

答案 0 :(得分: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 :(得分:-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
})

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

请注意,forEach中的getAdditionalInformations不会等到数组的下一个条目完成。

您可以将普通旧代码用于(var i = 0; ....