search

Home  >  Q&A  >  body text

node.js - How to pass values ​​to array in asynchronous callback?

I send an http post request, get the value returned, and then call back. I want to require this file to other requests, but I don’t know how to take it out and save it; `

var req= http.request(options,function(res){

        var size=0;
        var chunks=[];
           res.on('data', function (chunk) {
               size += chunk.length;
               chunks.push(chunk);
               
        });
        res.on('end',function(){    
            var datas = Buffer.concat(chunks,size);
        //console.log(datas)
            var htmldata = JSON.parse(datas.toString());
            
            callback1(htmldata);
        })
})

req.write(data);
req.end();

}

module.exports=request;
//Other requests
var king=require('./yinhttp.js')//Introduction;`

var arr=[];
king(function(v){
//获取值,push进数组;
})

I tried for a long time, but the value was not transmitted outside.
I found the reason. It was because of the asynchronous operation. I defined the array, but when it ran to king(function(v){}), because of the asynchronous operation , I have run the following code, which caused me to print out the problem

女神的闺蜜爱上我女神的闺蜜爱上我2720 days ago773

reply all(1)I'll reply

  • 给我你的怀抱

    给我你的怀抱2017-06-17 09:18:38

    This is the reason why res supports streaming and how it is written, so you can’t get it

    reply
    0
  • Cancelreply