title: Firebase Cloud Functions - Cannot read property 'forEach' of undefined
body: <p>I have something like this:</p>
  
  <pre><code>const promises = [];
  
      l = niz.length;
      for (i = 0; i &lt; l; i++) {
        if(niz[i].length === 0) {
            continue;
        }
  
        promises.push(admin.messaging().sendToDevice(niz[i], payload, options));
      }
  
     return Promise.all(promises).then((response) =&gt; {
          return cleanupTokens(response, tokens);
          //return resolve(); 
      }).then(() =&gt; {
          return resolve();
      });
  </code></pre>
  
  <p>but always I have crash in firebase logs:</p>
  
  <blockquote>
    <p>TypeError: Cannot read property 'forEach' of undefined
        at cleanupTokens (/user_code/index.js:193:20)
        at Promise.all.then (/user_code/index.js:169:20)
        at process._tickDomainCallback (internal/process/next_tick.js:135:7)</p>
  </blockquote>
  
  <p>Response is:</p>
  
  <blockquote>
    <p>response:  [ { results: [ [Object] ],
        canonicalRegistrationTokenCount: 0,
        failureCount: 0,
        successCount: 1,
        multicastId: 5591935326806715000 } ]</p>
    
    <p>response: undefined</p>
  </blockquote>
  
  <p>cleanup is:</p>
  
  <pre><code>function cleanupTokens(response, tokens) {
  
  // For each notification we check if there was an error.
  const tokensToRemove = {};
  
  console.log('response: ', response);
  
  console.log('response: ', JSON.stringify(response.results));
  
  response.results.forEach((result, index) =&gt; {
         const error = result.error;
  
         if (error) {
           console.error('Failure sending notification to', tokens[index], error);
  
           // Cleanup the tokens who are not registered anymore.
           if (error.code === 'messaging/invalid-registration-token' ||
               error.code === 'messaging/registration-token-not-registered' ||
               error.code === 'messaging/invalid-recipient') {
  
             tokensToRemove[`/tokens/${tokens[index]}/g`] = null;
             tokensToRemove[`/tokens/${tokens[index]}/l/0`] = null;
             tokensToRemove[`/tokens/${tokens[index]}/l/1`] = null;
           }
         }
     });
  
     return admin.database().ref().update(tokensToRemove);
  }
  </code></pre>
  
  <p>Any help with cleanup tokens?</p>