Skip to content

Why is my function saying that a promise isn’t being handled correctly?

New to Typescript. Wrote this function but I can’t figure out why it’s giving the error below. I commented the 2 lines that the errors are pointing to.

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp();

exports.createUser = functions.https.onCall(async (data, context) => {
  console.log('_createUser: ');
  const uid = context?.auth?.uid;
  if (uid) {
    const username = data.user;
    const email = data.email;

    //Check to see if that username already exists
    const qData = await admin.firestore().collection('users').where('username', '==', username).limit(1).get();
    qData.forEach(doc => {
      const otherUsername = doc.get('username').toString();

      if (otherUsername) {
        console.log('_createUser: Username is already in use.');
        return 'Username is already in use.'
      }
      else {
        //Create collection for this user's friends list
        const friendsColl = 'friends_' + uid;
        const friendsDoc = admin.firestore().collection(friendsColl).doc();
        friendsDoc.set({ //Error #1 is here
          //Forces the collection to exist
          exists: 1, 

          //Other useful data
          createDate: admin.firestore.FieldValue.serverTimestamp(),
          modifiedDate: admin.firestore.FieldValue.serverTimestamp(),
          ownerUsername: username,
          ownerUID: uid, //
          rowType: 'B', //N = normal, B = backend (created for server side reasons)
        })

        const userDoc = admin.firestore().collection('users').doc(uid); // use uid as document ID
        userDoc.set({ //Error #2 is here
          createDate: admin.firestore.FieldValue.serverTimestamp(),
          modifiedDate: admin.firestore.FieldValue.serverTimestamp(),
          username: username,
          email: email,
          stat: 1, //0 = banned, 1 = normal
          uid: uid,
          friendsColl: friendsColl,
        })
        return console.log('_createUser_finished');
      };
    });    
  }
  else {
    return console.log('_createUser_Error: User is not authorized');
  };
});

48:9 error Promises must be handled appropriately or explicitly marked as ignored with the void operator @typescript-eslint/no-floating-promises

61:9 error Promises must be handled appropriately or explicitly marked as ignored with the void operator @typescript-eslint/no-floating-promises

Answer

You need to use then with set method to return promise. Like this

    friendsDoc.set({ //Error #1 is here
      //Forces the collection to exist
      exists: 1, 

      //Other useful data
      createDate: admin.firestore.FieldValue.serverTimestamp(),
      modifiedDate: admin.firestore.FieldValue.serverTimestamp(),
      ownerUsername: username,
      ownerUID: uid, //
      rowType: 'B', //N = normal, B = backend (created for server side reasons)
    }).then(result => {});