for 루프를 반복 한 다음 함수 JS 호출

Aug 19 2020

그래서 우체부에게 하나 이상의 물건을 넣을 수는 없습니다. 내가 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 /)의 ServerResponse.setHeader (_http_outgoing.js : 518 : 11)에서 클라이언트로 보낸 후 헤더를 설정할 수 없습니다. 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) /Users/jaredschau/Desktop/cod-tracker/routes/posts.js:29의 ServerResponse.json (/Users/jaredschau/Desktop/cod-tracker/node_modules/express/lib/response.js:267:15) : 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를 거부하여 발생했습니다. 처리되지 않은 약속 거부시 노드 프로세스를 종료하려면 CLI 플래그를 사용하십시오.--unhandled-rejections=strict(https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode 참조). (거부 ID : 1) (node ​​: 19134) [DEP0018] DeprecationWarning : 처리되지 않은 약속 거부는 사용되지 않습니다. 앞으로 처리되지 않는 promise 거부는 0이 아닌 종료 코드로 Node.js 프로세스를 종료합니다.

답변

1 Kumar Aug 19 2020 at 10:05

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;
    })
  })

그것이 당신을 위해 작동하는지 알려주세요

elpmid Aug 19 2020 at 10:05

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))

반환 된 값은 플레이어 배열에서 생성 된 프라 미스의 출력 배열입니다. 도움이되기를 바랍니다. 건배