Bir for döngüsü üzerinden döngü ve ardından bir JS işlevi çağırma

Aug 19 2020

Bu yüzden postacıya birden fazla nesne koymayı seçemiyorum. Console.log yaptığımda dizinin tüm nesnelerini alıyorum (çıkarıp player ile değiştirdiğim savaş etiketleri)

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

konsol düğümünde hata alıyorum: 19134) UnhandledPromiseRejectionWarning: Hata [ERR_HTTP_HEADERS_SENT]: ServerResponse.setHeader'da (_http_outgoing.js: 518: 11) ServerResponse.header'da (/ Users / jaredschau) istemciye gönderildikten sonra başlıklar ayarlanamaz Desktop / cod-tracker / node_modules / express / lib / response.js: 771: 10) ServerResponse.send'de (/Users/jaredschau/Desktop/cod-tracker/node_modules/express/lib/response.js:170:12) ServerResponse.json'da (/Users/jaredschau/Desktop/cod-tracker/node_modules/express/lib/response.js:267:15) /Users/jaredschau/Desktop/cod-tracker/routes/posts.js:29 adresinde: 25 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: İşlenmemiş söz reddi.Bu hata, ya catch bloğu olmayan bir zaman uyumsuz işlevin içine atılmaktan ya da .catch () ile işlenmemiş bir sözün reddedilmesinden kaynaklanıyordu. İşlenmemiş söz reddi durumunda düğüm sürecini sonlandırmak için CLI bayrağını kullanın--unhandled-rejections=strict(bkz. https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (reddetme kimliği: 1) (düğüm: 19134) [DEP0018] Kullanımdan Kaldırılma Uyarısı: İşlenmemiş söz reddi kullanımdan kaldırıldı. Gelecekte, ele alınmayan vaat retleri, Node.js sürecini sıfır olmayan bir çıkış koduyla sonlandıracaktır.

Yanıtlar

1 Kumar Aug 19 2020 at 10:05

Görünüşe göre API.MWBattleData('Player1')bir söz veriyor. O zaman bunu Promise.all, tüm vaatleri sırayla çözecek ve tüm vaatler için size bir dizi sonuç döndürecek şekilde başarabilirsiniz.

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

Senin işine yarar mı bileyim

elpmid Aug 19 2020 at 10:05

Promise.all () yöntemini, girdinin vaat ettiği sonuçların bir dizisini çözen yinelenebilir sözler oluşturmak için kullanabilirsiniz. Belgelere bakın: Promise.all ()

Bir dizi kullanıcınız olduğunu anladım.

const players = [player1, player2, player3];

Bunlardan bir promise girdisi oluşturmak için, bunu bir dizi döndüren array.map yöntemini kullanarak yapabilirsiniz.

Promise.all(players.map(player => API.MWBattleData(player))).then(values => console.log(values))

Döndürülen değerler, oyuncular dizinizden yaratılan vaatlerin bir çıktı dizisidir. Umut ediyorum bu yardım eder. Şerefe