Home > Software engineering >  How to handle async/await and promises in node.js confusion
How to handle async/await and promises in node.js confusion

Time:12-13

I have checked tons of similiar problems all data, I am so confused. This is returning the same result whether the phone number is in the DB or not. Other versions with async and promises have been crashing the app. Please help

How can I get a value from Firebase realtime DB using the admin SDK and use that value to determine the output. Also it seems abnormally slow at times for some reason

auth.controller.js

const validate = require('../utils/validate');
const { getItem, setItem } = require('../utils/firebase');
const { generatePin } = require('../utils/auth');
const argon2 = require('argon2');
const { error } = require('console');
const { networkInterfaces } = require('os');
const exp = require('constants');

exports.connect = async function (req, res) {
    const { phone } = req.body;
    if (!phone) {
        res.status(400).json({ message: 'Error, phone number is invalid or not registered'})
    } else {
        if(!validate.phoneNumber(phone))  {
            res.status(400).json({ message: 'Error, phone number is invalid or not registered' })              
        } else {
            const result = await generatePin();
            item = await setItem('clients', 'phone', phone, 'hash', result.hash)
            console.log(item)
            if(!item) {
                res.status(200).json({ message: 'Success', pin: result.pin})
            }  else {
                res.status(400).json({ message: 'Error, phone number is invalid or not registered' })
            }
            var currentTime = Date.now();   
            var expiryTime = currentTime   60;     
            setItem('clients', 'phone', phone, 'hashExpiry', expiryTime)
        }            
    }

firebase.js

const { on } = require("events");
var admin = require("firebase-admin");
// Import Admin SDK
const { getDatabase } = require('firebase-admin/database');
const { type } = require("os");

var serviceAccount = require("../fedex-3a42e-firebase-adminsdk-r96f1-7249eaf87b.json");
admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "https://fedex-3a42e-default-rtdb.firebaseio.com/"
});

const db = getDatabase()

function getItem(itemRef, child, val) {
    const dbRef = db.ref(itemRef);    
    dbRef.orderByChild(child).equalTo(val).on("value", (data) => {
        return data.val();       
    }); 
}

async function setItem(itemRef, child, val, key, pushedVal) {
    const value = await getItem(itemRef, child, val);
    console.log('val', value)
    if(value) {
        finallySetItem(value, itemRef, pushedVal);
        return true
    } else  {
        return false
    }         
}

function finallySetItem(data, itemRef, pushedVal) {
    console.log(data)
    if(data) {
        var itemKey = Object.keys(data)[0];
        console.log(itemKey)
        const dbRef = db.ref(itemRef   '/'   itemKey    '/'   key);
        dbRef.set(pushedVal);        
    }
}

module.exports = { getItem, setItem }

CodePudding user response:

This won't work:

function getItem(itemRef, child, val) {
    const dbRef = db.ref(itemRef);    
    dbRef.orderByChild(child).equalTo(val).on("value", (data) => {
        return data.val();       
    }); 
}

You're passing your callback to on(), and on() won't do anything with the value you return in there.

More likely you want to use once() and return the value asynchronously from there:

async function getItem(itemRef, child, val) {
    const dbRef = db.ref(itemRef);    
    const data = await dbRef.orderByChild(child).equalTo(val).once("value");
    return data.val();       
}
  • Related