尝试使用函数调用返回时,array.map 给出未定义 [重复]

Posted

技术标签:

【中文标题】尝试使用函数调用返回时,array.map 给出未定义 [重复]【英文标题】:array.map gives undefined when trying to return using a function call [duplicate] 【发布时间】:2018-04-13 19:41:33 【问题描述】:

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

这是我的代码 sn-p,我不确定这是否是将数据放入数组的正确方法。

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

我的return语句之前的日志是完美的,如下:

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

但最终的日志给出了 undefined :

This is responseArray:  [ undefined, undefined ]

此外,给出未定义的日志首先打印,而不是响应状态日志。

编辑正如@thomas 在评论中提到的那样,我也曾尝试将 return 恰好放在 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 提到的 forEach,它给了我这个:

This is responseArray:  [] 

编辑 2

正如 thomas 所说,我也尝试了返回的 promise.all():

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

【问题讨论】:

【参考方案1】:

我假设 request.get 返回一个承诺?如果是,那么这应该工作:

    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 来等待两个请求都完成。

【讨论】:

不,我试过了,它返回一个完整的函数结构而不是响应 我确实想到了这一点,但我希望有一个解决方法来保证,而不是说它不好或其他什么,但我已经在我的请求模块中有一个回调并且不想添加更多这样的东西。 我用了promise,结果还是一样,请检查我的EDIT2 请求对象来自哪里?你在用 Witch lib 吗? 我正在使用这个库npmjs.com/package/request

以上是关于尝试使用函数调用返回时,array.map 给出未定义 [重复]的主要内容,如果未能解决你的问题,请参考以下文章

为啥返回带有箭头函数的对象时,array.map 中需要 return 关键字?

Array的 map() 和 reduce()

数组的方法 Array.map();Array.every()和Array.some();数组的indexof();

向返回承诺数组的 Array.map 调用添加毫秒延迟

酶测试问题返回未定义

JavaScript中的map()函数