Javascript 具有多个获取请求的“退出承诺”
我需要合并API中的数据。我首先调用一个端点,该端点给我一个id列表,然后我对每个id进行请求。我的目标是返回一个包含所有请求响应的列表,但我在承诺中迷失了自己 我的代码在NodeJS上运行。代码如下:Javascript 具有多个获取请求的“退出承诺”,javascript,node.js,promise,async-await,fetch,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
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()
我发现以下错误:wait仅在异步函数中对此行有效:
let additionalInformations = await getAdditionalInformations(raw_id['id'])
请帮我回答promise和async/Wait问题。你就快到了,只是括号里有一点小错误:
// 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
}
您缺少forEach之后的异步
const parseIds=异步原始\u id=>{
让id=[]
原始id.forEachasync函数原始id{
让信息S={
//对象,该对象包含来自第一个请求的数据
}
让更多信息等待
getAdditionalInformationsraw_id['id']
设merged={…informations,…additionalInformations}
id.pushmerge
}
返回ID
}foreach中的回调不是异步的。请在functionraw\u id之前放置一个异步,使其看起来像:async functionraw\u id:。这至少会使等待错误消失。谢谢,它会删除错误,但最后我得到一个空数组。。。我尝试在控制台上打印var,从请求中得到响应,但数组仍然是空的。嘿,这不起作用-forEach不知道如何等待它的元素,forEach中的async也不会等待它内部创建的承诺的内容。这需要是一个为。。。循环或带有Promise.all的.map的实例:]