Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
107 views
in Technique[技术] by (71.8m points)

javascript - Why is my array coming back undefined outside of the function?

I am trying to get "msg" out of this function to do math on it and it keeps coming back undefined. However when within the function I can read the data but cant do math on it.

let getArr = []
      const https = require('https')
        const options = {
          hostname: 'financialmodelingprep.com',
          port: 443,
          path: '/api/v3/quote/TSLA?apikey=?apikey=demo',
          method: 'GET'
        }
        
        const req = https.request(options, (res) => {
         
             res.on('data', (data) => {
             data = JSON.parse(data)
             data.map(( msg ) => {
                 //console.log(msg)
                 getArr.push(msg)
             })
          })        
        })  
     console.log(getArr.slice(-1)[0])     
question from:https://stackoverflow.com/questions/65865538/why-is-my-array-coming-back-undefined-outside-of-the-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The code has two issues.

  1. Trying to access the results of processing the https request, the msg entries held in getArr, before the response from the request has been received:

    • data.map(( msg ) => {... is executed after the response is received in a call back function.
    • console.log(getArr.slice(-1)[0]) executes synchronously after issuing the request to the browser (which may or may not have initiated a network request yet) and certainly before the callback has been called.

    Canonical answer: How do I return the response from an asynchronous call?

  2. HTTP(S) responses are sent in packets and there is no guarantee that the first will contain all the JSON text there is to receive.

    • code must concatenate chunks of data passed to on("data", ) and only attempt to parse the full string in an on('end', ... ) callback handler.

    Previously answered to: SyntaxError: Unexpected end of JSON input at JSON.parse (... at IncomingMessage...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...