[英]Looping through a for loop then calling a function JS
所以我不能让它选择输入 postman 多于一个 object。当我 console.log 它时,我得到了数组的所有对象(我取出并替换为播放器的战场标签)
router.get('/cod/', (req, res) => {
const pdata = {}
console.log(req.params)
API.login(process.env.EMAIL, process.env.PASSWORD).then((output) => {
// Players array,
players = ['player1', 'player2', 'player3']
// map through array and create promise for each player and store it in an array
promises = players.map(player => API.MWBattleData(player))
// Pass all promises to Promise.all
// Result will be an array of individual output of each promise
Promise.all(promises)
.then(result => {
// Loop through result, and assign the output to pdata
result.forEach((output, index) => {
// index + 1 because starting index will be zero
pdata[`p${index + 1}`] = output
res.json(pdata);
})
})
})
});
我在控制台节点中收到错误:19134) UnhandledPromiseRejectionWarning: 错误 [ERR_HTTP_HEADERS_SENT]: 在将标头发送到 ServerResponse.setHeader (_http_outgoing.js:518:11) at ServerResponse.header (/Users/jaredschau/) 的客户端后无法设置标头桌面/cod-tracker/node_modules/express/lib/response.js:771:10) 在 ServerResponse.send (/Users/jaredschau/Desktop/cod-tracker/node_modules/express/lib/response.js:170:12)在 ServerResponse.json (/Users/jaredschau/Desktop/cod-tracker/node_modules/express/lib/response.js:267:15) 在 /Users/jaredschau/Desktop/cod-tracker/routes/posts.js:29: 25 在 Array.forEach () 在 /Users/jaredschau/Desktop/cod-tracker/routes/posts.js:26:24 在 processTicksAndRejections (internal/process/task_queues.js:97:5) (node:19134) UnhandledPromiseRejectionWarning:未处理的 promise 拒绝。 此错误源于在没有 catch 块的情况下抛出异步 function,或者拒绝未使用 .catch() 处理的 promise。 要在未处理的 promise 拒绝时终止节点进程,请使用 CLI 标志--unhandled-rejections=strict
(请参阅 https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode)。 (拒绝 ID:1)(节点:19134)[DEP0018] DeprecationWarning:未处理的 promise 拒绝已弃用。 以后,未处理的 promise 拒绝将以非零退出代码终止 Node.js 进程。
看起来API.MWBattleData('Player1')
返回一个 promise。然后您可以通过Promise.all
实现此目的,它将按顺序解决所有承诺并返回所有承诺的结果数组
// Players array,
players = ['player1', 'player2', 'player3', ...]
// map through array and create promise for each player and store it in an array
promises = players.map(player => API.MWBattleData(player))
// Pass all promises to Promise.allSettled
Promise.allSettled(promises)
.then(result => { // Result will be an array of individual output of each promise
// Loop through result, and assign the output to pdata
result.forEach((output, index) => {
// index + 1 because starting index will be zero
pdata[`p${index + 1}`] = output.value;
})
})
让我知道这是否适合你
您可以使用 promise.all() 方法创建一个可迭代的承诺,它解析输入承诺的结果数组。 请参阅文档: Promise.all()
我推断您有一系列用户。
const players = [player1, player2, player3];
要从它们中创建一个 promise 输入,您可以使用返回数组的 array.map 方法这样做。
Promise.all(players.map(player => API.MWBattleData(player))).then(values => console.log(values))
返回值是 output 的数组,由您的玩家数组创建的承诺。 我希望它有所帮助。 干杯
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.