当尝试使用函数调用返回时,array.map给出undefined

时间:2017-11-01 13:13:27

标签: javascript angularjs arrays node.js typescript

我在处理数组数据后尝试将结果存储在另一个数组中,但我总是得到[undefined,undefined]作为我的响应数组。

这是我的代码段,我不确定这是否是将数据导入数组的正确方法。

function ping(urls) {
  let responseArray = urls.map(function(url) {
    request.get(url, {
      timeout: 5000
    }, function(err, res, body) {
      if (!err) {
        console.log(`Response status from ${url} is ${res.statusCode}`);
        return {
          url: url,
          status: res.statusCode
        };
      } else {
        console.log(`Exception occurred while connecting to ${url} ERR:: ${err}`);
        return {
          url: url,
          status: 0
        };
      }
    });
  });
  console.log("This is responseArray: ", responseArray);
}

返回语句之前的日志非常完美,如下所示:

Response status from https://google.com is 200
Response status from https://github.com is 200

但是最终的日志给出了undefined:

This is responseArray:  [ undefined, undefined ]

首先打印给定undefined的日志而不是响应状态日志。

编辑正如@thomas在评论中提到的那样,我也尝试将回复放在request.get之前,但那又回到了我

This is responseArray:  [ Request {                     
    domain: null,                                       
    _events:                                            
     { error: [Function: bound ],                       
       complete: [Function: bound ],                    
       pipe: [Function] },                              
    _eventsCount: 3,                                    
    _maxListeners: undefined,                           
    timeout: 5000,                                      
    uri:                                                
     Url {                                              
       protocol: 'https:',                              
       slashes: true,                                   
       auth: null,                                      
       host: 'google.com',                              
       port: 443,                                       
       hostname: 'google.com',                          
       hash: null,                                      
       search: null,                                    
       query: null,                                     
       pathname: '/',                                   
       path: '/',                                       
       href: 'https://google.com/' },                   
    callback: [Function],                               
    method: 'GET',                                      
    readable: true,                                     
    writable: true,                                     
    explicitMethod: true,                               
    _qs:                                                
     Querystring {                                      
       request: [Circular],                             
       lib: [Object],                                   
       useQuerystring: undefined,                       
       parseOptions: {},                                
       stringifyOptions: {} },                          
    _auth:                                              
     Auth {                                             
       request: [Circular],                             
       hasAuth: false,                                  
       sentAuth: false,                                 
       bearerToken: null,                               
       user: null,                                      
       pass: null },                                    
    _oauth: OAuth { request: [Circular], params: null },
    _multipart:                                         
     Multipart {                                        
       request: [Circular],                             
       boundary: 'e629bc7c-50e0-423f-a5d2-30038ac037e3',
       chunked: false,                                  
       body: null },                                    
    _redirect:                                          
     Redirect {                                         
       request: [Circular],                             
       followRedirect: true,                            
       followRedirects: true,                           
       followAllRedirects: false,                       
       followOriginalHttpMethod: false,                 
       allowRedirect: [Function],                       
       maxRedirects: 10,                                
       redirects: [],                                   
       redirectsFollowed: 0,                            
       removeRefererHeader: false },                    
    _tunnel:                                            
     Tunnel {                                           
       request: [Circular],                             
       proxyHeaderWhiteList: [Object],                  
       proxyHeaderExclusiveList: [] },                  
    headers: { host: 'google.com' },                    
    setHeader: [Function],                              
    hasHeader: [Function],                              
    getHeader: [Function],                              
    removeHeader: [Function],                           
    localAddress: undefined,                            
    pool: {},                                           
    dests: [],                                          
    __isRequestRequest: true,                           
    _callback: [Function],                              
    proxy: null,                                        
    tunnel: true,                                       
    setHost: true,                                      
    originalCookieHeader: undefined,                    
    _disableCookies: true,                              
    _jar: undefined,                                    
    port: 443,                                          
    host: 'google.com',                                 
    path: '/',                                          
    httpModule:                                         
     { Server: [Object],                                
       createServer: [Function],                        
       globalAgent: [Object],                           
       Agent: [Object],                                 
       request: [Function],                             
       get: [Function] },                               
    agentClass: { [Function: Agent] super_: [Object] }, 
    agent:                                              
     Agent {                                            
       domain: null,                                    
       _events: [Object],                               
       _eventsCount: 1,                                 
       _maxListeners: undefined,                        
       defaultPort: 443,                                
       protocol: 'https:',                              
       options: [Object],                               
       requests: {},                                    
       sockets: {},                                     
       freeSockets: {},                                 
       keepAliveMsecs: 1000,                            
       keepAlive: false,                                
       maxSockets: Infinity,                            
       maxFreeSockets: 256,                             
       maxCachedSessions: 100,                          
       _sessionCache: [Object] } },                     
  Request {                                             
    domain: null,                                       
    _events:                                            
     { error: [Function: bound ],                       
       complete: [Function: bound ],                    
       pipe: [Function] },                              
    _eventsCount: 3,                                    
    _maxListeners: undefined,                           
    timeout: 5000,                                      
    uri:                                                
     Url {                                              
       protocol: 'https:',                              
       slashes: true,                                   
       auth: null,                                      
       host: 'github.com',                              
       port: 443,                                       
       hostname: 'github.com',                          
       hash: null,                                      
       search: null,                                    
       query: null,                                     
       pathname: '/',                                   
       path: '/',                                       
       href: 'https://github.com/' },                   
    callback: [Function],                               
    method: 'GET',                                      
    readable: true,                                     
    writable: true,                                     
    explicitMethod: true,                               
    _qs:                                                
     Querystring {                                      
       request: [Circular],                             
       lib: [Object],                                   
       useQuerystring: undefined,                       
       parseOptions: {},                                
       stringifyOptions: {} },                          
    _auth:                                              
     Auth {                                             
       request: [Circular],                             
       hasAuth: false,                                  
       sentAuth: false,                                 
       bearerToken: null,                               
       user: null,                                      
       pass: null },                                    
    _oauth: OAuth { request: [Circular], params: null },
    _multipart:                                         
     Multipart {                                        
       request: [Circular],                             
       boundary: 'e15018e6-6f56-4d42-9a0b-ff471b3e0995',
       chunked: false,                                  
       body: null },                                    
    _redirect:                                          
     Redirect {                                         
       request: [Circular],                             
       followRedirect: true,                            
       followRedirects: true,                           
       followAllRedirects: false,                       
       followOriginalHttpMethod: false,                 
       allowRedirect: [Function],                       
       maxRedirects: 10,                                
       redirects: [],                                   
       redirectsFollowed: 0,                            
       removeRefererHeader: false },                    
    _tunnel:                                            
     Tunnel {                                           
       request: [Circular],                             
       proxyHeaderWhiteList: [Object],                  
       proxyHeaderExclusiveList: [] },                  
    headers: { host: 'github.com' },                    
    setHeader: [Function],                              
    hasHeader: [Function],                              
    getHeader: [Function],                              
    removeHeader: [Function],                           
    localAddress: undefined,                            
    pool: {},                                           
    dests: [],                                          
    __isRequestRequest: true,                           
    _callback: [Function],                              
    proxy: null,                                        
    tunnel: true,                                       
    setHost: true,                                      
    originalCookieHeader: undefined,                    
    _disableCookies: true,                              
    _jar: undefined,                                    
    port: 443,                                          
    host: 'github.com',                                 
    path: '/',                                          
    httpModule:                                         
     { Server: [Object],                                
       createServer: [Function],                        
       globalAgent: [Object],                           
       Agent: [Object],                                 
       request: [Function],                             
       get: [Function] },                               
    agentClass: { [Function: Agent] super_: [Object] }, 
    agent:{...} and ...

我也尝试过按照renzo提到的每个,它给了我这个:

This is responseArray:  [] 

编辑2

正如托马斯所提到的,我也尝试了promise.all()返回:

This is responseArray:  [ undefined, undefined ]
Response status from https://google.com is 200
Response status from https://github.com is 200

1 个答案:

答案 0 :(得分:0)

我假设request.get返回一个promise?如果是,那么这应该有效:

    function ping(urls) {
      let responseArray = urls.map(function(url) {
        return request.get(url, {
          timeout: 5000
        }, function(err, res, body) {
      if (!err) {
        console.log(`Response status from ${url} is ${res.statusCode}`);
        return {
          url: url,
          status: res.statusCode
        };
      } else {
        console.log(`Exception occurred while connecting to ${url} ERR:: ${err}`);
        return {
          url: url,
          status: 0
        };
      }
    });
  });
  Promise.all(responseArray).then(function() {
    console.log("This is responseArray: ", responseArray);
  }) 
}

您需要promise.all等待两个请求完成。