forループをループしてから関数JSを呼び出す
だから私はそれを郵便配達員に複数のオブジェクトを選択させることができません。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.header(/ Users / jaredschau / Desktop / cod-tracker / node_modules / express / lib / response.js:771:10)at 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 at Array.forEach()at /Users/jaredschau/Desktop/cod-tracker/routes/posts.js:26:24 at processTicksAndRejections(internal / process / task_queues.js:97:5)(node:19134)UnhandledPromiseRejectionWarning:未処理の約束の拒否。このエラーは、catchブロックなしで非同期関数の内部をスローするか、.catch()で処理されなかったpromiseを拒否することによって発生しました。未処理のPromise拒否でノードプロセスを終了するには、CLIフラグを使用します--unhandled-rejections=strict
(https://nodejs.org/api/cli.html#cli_unhandled_rejections_modeを参照してください)。(拒否ID:1)(ノード:19134)[DEP0018]非推奨警告:未処理のプロミス拒否は非推奨になりました。将来、処理されないpromise拒否は、ゼロ以外の終了コードでNode.jsプロセスを終了します。
回答
API.MWBattleData('Player1')
約束を返すように見えます。次に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))
戻り値は、players配列から作成されたpromiseによる出力の配列です。お役に立てば幸いです。乾杯