0

I'm grabbing some values from an API and adding them to an array which I can get to display correctly. var total = [points, rebounds, assists, steals, blocks, tov] However I want to add the values within the array together and display the sum of them as an output, but using the + operator just appends each value to the end end of the last. I have searched and tried a bunch of solutions on the site, but things like parseInt seem to throw a UnhandledPromiseRejectionWarning: RangeError Any help would be greatly appreciated.

Code below:

var express = require('express')
var fetch = require('isomorphic-fetch')
var app = express()

async function nbaFetch(){
    let result = await fetch('https://stats.nba.com/stats/playerdashboardbygeneralsplits?DateFrom=&DateTo=&GameSegment=&LastNGames=0&LeagueID=00&Location=&MeasureType=Base&Month=0&OpponentTeamID=0&Outcome=&PORound=0&PaceAdjust=N&PerMode=Totals&Period=0&PlayerID=201935&PlusMinus=N&Rank=N&Season=2018-19&SeasonSegment=&SeasonType=Regular+Season&ShotClockRange=&Split=general&VsConference=&VsDivision=', {
        mode: 'cors',
        method: "GET", // *GET, POST, PUT, DELETE, etc.
        headers: {
            
        "accept-encoding": "Accepflate, sdch",
        "accept-language": "he-IL,he;q=0.8,en-US;q=0.6,en;q=0.4",
        "cache-control": "max-age=0",
        connection: "keep-alive",
        host: "stats.nba.com",
        referer: "http://stats.nba.com/",
        "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36"
        },
    })

    let nbaFileStruct = await result.json()

    
    return nbaFileStruct
}
app.use('/', async function (req, res, next) {
    let result = await nbaFetch().catch(error => console.log(error))

    // Grab all the values i want and add the fantasy multipliers
    var points = (JSON.stringify(result.resultSets[0].rowSet[0][26]))*1
    var rebounds = (JSON.stringify(result.resultSets[0].rowSet[0][18]))*1.5
    var assists = (JSON.stringify(result.resultSets[0].rowSet[0][19]))*1.5
    var tov = (JSON.stringify(result.resultSets[0].rowSet[0][20]))*-2
    var steals = (JSON.stringify(result.resultSets[0].rowSet[0][21]))*2
    var blocks = (JSON.stringify(result.resultSets[0].rowSet[0][22]))*2

    // Add multiplied results into a single array
    var total = [points, rebounds, assists, steals, blocks, tov]

    //Add array values together

    // Send result to client
    res.send(total)
    
})

app.listen(3001, console.log("I'm a server and I am listening on port 3001"))

1 Answers1

0

Firstly, parse the values to a number - then use reduce to add them up:

var points = parseInt(JSON.stringify(result.resultSets[0].rowSet[0][26]))*1
var rebounds = parseInt(JSON.stringify(result.resultSets[0].rowSet[0][18]))*1.5
var assists = parseInt(JSON.stringify(result.resultSets[0].rowSet[0][19]))*1.5
var tov = parseInt(JSON.stringify(result.resultSets[0].rowSet[0][20]))*-2
var steals = parseInt(JSON.stringify(result.resultSets[0].rowSet[0][21]))*2
var blocks = parseInt(JSON.stringify(result.resultSets[0].rowSet[0][22]))*2
var total = [points, rebounds, assists, steals, blocks, tov]
var sum = total.reduce((acc, curr) => acc + curr, 0);
//Do something with sum
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • I've tried a few things like this, but i seem to be getting an error `UnhandledPromiseRejectionWarning: RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: 3307` Is there an issue with creating a new function within an async function? – gyroscopeboy Mar 13 '19 at 09:15
  • @gyroscopeboy remove `JSON.stringfy` like this `var points = (result.resultSets[0].rowSet[0][26])*1` then add like this `var total = [points, rebounds, assists, steals, blocks, tov] var sum = total.reduce((total, sum) => total + sum) res.send(sum) ` – Aadil Mehraj Mar 13 '19 at 09:18
  • @AadilMehraj Thanks for the suggestion, however that seems to throw a promise error too...I think i need stringify to access the values from the data source. I don't have control over how i'm being fed the data – gyroscopeboy Mar 13 '19 at 09:26
  • It worked fine for me. Possibly the promise error is in fetch response, can you confirm abt the promise errror – Aadil Mehraj Mar 13 '19 at 09:53
  • @AadilMehraj Terminal error is: ``` (node:6858) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:6858) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. ``` – gyroscopeboy Mar 13 '19 at 10:07
  • try to enclose `nbafetch` call inside try-catch instead of catching directly – Aadil Mehraj Mar 13 '19 at 10:29
  • Thanks guys, this seems to work and i can get it to log to the console...just seems to break when I go to send the result to the client and throws an error with the code = the result. Will investigate – gyroscopeboy Mar 13 '19 at 20:24