How to use Promise value outside an async function? [duplicate] - javascript

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How can I access the value of a promise?
(14 answers)
Closed 6 days ago.
I'm having issues when I'm trying to use the value of a Async Function ouside of it:
I have an async function that obtains the user's data as follows:
async function getUserDataPromise() {
const uid = Firebase.auth().currentUser.uid
const docuRef = doc(firestore, `Usuarios/${uid}`)
const snapshot = await getDoc(docuRef)
const nombre = snapshot.data().Nombre
const apellido = snapshot.data().Apellido
const id = snapshot.data().ID
const email = snapshot.data().Email
const rol = snapshot.data().Rol
return [nombre, apellido, id, email, rol]
}
Then I try to use that info like this:
function getUserData() {
var thisNombre
Promise.resolve(getUserDataPromise()).then(value => {
thisNombre = value[0]
console.log(value[0]) //Returns what I expected: a string with a name
})
return thisNombre
}
console.log('Nombre: ' + getUserData())// Returns: Nombre: undefined
I know I can use the data inside the 'Promise.resolve' but I need to use it outside of it. How can I do it?

Related

Loop through Scripts and push all regex matching strings to an aray, but the array is somehow empty [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Reading and returning multiple files in Node.js using fs.readFile
(5 answers)
Get data from fs.readFile [duplicate]
(17 answers)
Closed 3 months ago.
I'm looping through scripts in a folder. For each script i check for regex matchings. If a matching appears i want to create an object out of it and push the object to an array. Then I want to console.log the Array but it's empty.
const { getServerFolders, getServerFolderElements } = require('./mainModules/getServerFolders.js')
var fs = require('fs');
const serverFoldersPath = "../electCon/src/scripts/"
function getFolderElements(folder) {
var variableObjArray = []
let folderName = folder.split('_')[0] //
// returns the files of the folder as an array
let serverFolderElements = getServerFolderElements(folderName);
serverFolderElements.forEach(element => {
//read the script
fs.readFile(serverFoldersPath + folderName + "/" + element , "utf-8", (err, data) => {
// throw if error
if(err) {return console.log(err)}
// find the variable with the # prefix
var scriptVariableNames = data.match(/#[^#]+#/g)
// if there is one or more variable in the script
if(scriptVariableNames) {
// for each variable in the script
scriptVariableNames.forEach(variable => {
let variableProp = variable.split("#")[1]
variableObject = {
sourceScript: element,
variableName : variable,
variableProp : variableProp,
variableDescription : "",
}
variableObjArray.push(variableObject)
})
}
})
})
console.log(variableObjArray)
}
when i log the array oe block earlier its full (but will log many times because of the loops), but as soon as i jump out a block its empty again
I have already tried to...
... log the variableObjArray earlier, but this way it would be in the for each loop.
... declare the object before, change the properties and than push it
Here to full code:
index.js
const { getServerFolders, getServerFolderElements } = require('./mainModules/getServerFolders.js')
var fs = require('fs');
const serverFoldersPath = "../electCon/src/scripts/"
function variableFinder(folder) {
var variableObjArray = []
let folderName = folder.split('_')[0] //
// returns the files of the folder as an array
let serverFolderElements = getServerFolderElements(folderName);
serverFolderElements.forEach(element => {
//read the script
fs.readFile(serverFoldersPath + folderName + "/" + element , "utf-8", (err, data) => {
// throw if error
if(err) {return console.log(err)}
// find the variable with the # prefix
var scriptVariableNames = data.match(/#[^#]+#/g)
// if there is one or more variable in the script
if(scriptVariableNames) {
// for each variable in the script
scriptVariableNames.forEach(variable => {
let variableProp = variable.split("#")[1]
variableObject = {
sourceScript: element,
variableName : variable,
variableProp : variableProp,
variableDescription : "",
}
variableObjArray.push(variableObject)
})
}
})
})
console.log(variableObjArray)
}
getServerFolders:
const { readdirSync } = require('fs');
const serverFoldersPath = "../electCon/src/scripts/"
function getServerFolders() {
let serverFolders = readdirSync(serverFoldersPath)
return serverFolders
}
function getServerFolderElements(server) {
let serverFolderElements = readdirSync(serverFoldersPath + server)
return serverFolderElements
}
module.exports = { getServerFolders, getServerFolderElements }
the scripts i want to loop trough:
hello mom #heeelp# #variable10# i hope stackoverflow can help me
not a variable #variablee# and some filler
Test-Connection #variable1#
I have already tried to...
... log the variableObjArray earlier, but this way it would be in the for each loop.
... declare the object before, change the properties and than push it
Note: its actually programmed in Electron and the variableFinder function is actually a ipcMain listener. I rewrote the function this way so no one will be confused. Thanks a lot :)

Why is my counter == 0 after i incremented it in a loop? [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How to get data from firestore DB in outside of onSnapshot
(1 answer)
Closed 1 year ago.
In my HTML i have the following code:
<div id="userCount" class="number count-to" data-from="0" data-to="" data-speed="1000" data-fresh-interval="20"></div>
And in my Javascript i'm trying to get the registered users count to display it in ' data-to="" ' from firebase.
My Javascript code:
let db = firebase.firestore();
let count = 0;
var div = $('#userCount');
db.collection("users").get().then((snapShot) => {
snapShot.forEach((doc) => {
count++;
});
});
div.data('to',count);
Why is that happening?
Because db.collection function is asyncronized one. Please take a look at following solution
let db = firebase.firestore();
let count = 0;
var div = $('#userCount');
db.collection("users").get().then((snapShot) => {
snapShot.forEach((doc) => {
count++;
});
div.data('to',count);
});

How to access a variable that's defined inside a .then() method, outside of the method - JavaScript? [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
In the code/example below, how can I access the likecount variable that's defined inside the db.collection()...then() method? I feel like I've tried every solution on the internet, but I've always gotten undefined as the result.
Code:
var parsed = path.split("/");
var likecount;
db.collection(parsed[0]).doc(parsed[1]).collection(parsed[2]).doc(parsed[3]).collection("likes").get().then(function(querySnapshot) {
likecount = querySnapshot.size
console.log(likecount)
})
The whole code (included where I try to access likecount):
firebase.auth().onAuthStateChanged(function(user) {
var query = db.collectionGroup("userPosts")
query.get().then(querySnapshot => {
setupPosts(querySnapshot.docs)
})
const posts = document.querySelector('.posts');
const setupPosts = (data) => {
let html = '';
data.forEach(doc => {
const post = doc.data();
const picURL = post.picURL;
var path = doc.ref.path;
var parsed = path.split("/");
var likecount;
db.collection(parsed[0]).doc(parsed[1]).collection(parsed[2]).doc(parsed[3]).collection("likes").get().then(function(querySnapshot) {
likecount = querySnapshot.size
console.log(likecount)
})
let li = `<li class="post">
<h3 class="content">${post.content}</h3>
<button class="comment" onclick="comment('${path}')">Comment</button>
<button class="like" onclick="like('${path}')">Like</button>
<span class="like-count">${likecount}</span>`;
li += (post.picURL ? `<img class="img" src="${picURL}" onclick="openImage('${picURL}')">` : ``);
li += `</li><br></br>`;
html += li
})
posts.innerHTML = html;
}

How do I use a promise to set the value of a variable and then post to db using Express? [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I want to use the node-zillow module to set the value of lastSoldDate but when I go to post I get the error lastSoldDate is undefined. this is what I have so far:
router.route('/add').post((req, res) => {
const address = req.body.address
const street = address.street
const zipcode = address.zipcode
const city = address.city
const state = address.state
paramaters = {
address: address.street,
citystatezip: address.city + ", " + address.state
}
zillow.get('GetDeepSearchResults', paramaters)
.then(function(results) {
date = results.response.results.result[0].lastSoldDate[0]
console.log(date)
return date;
}).then((date) => lastSoldDate = date)
const lastSoldPrice = req.body.lastSoldPrice
const newProperty = new property({
address:{
street,
zipcode,
city,
state,
},
lastSoldDate,
lastSoldPrice
})
newProperty.save()
.then(() => res.json('Property added!'))
.catch(err => res.status(400).json('Error: ' + err))
})

How to retrieve the content of a variable that is in a function? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I created this function:
var IDOfUserToKill = 'tralala';
export function getIDOfUserToKill(userID, gameID) {
let path = '/games/' + gameID + '/users/' + userID;
fb.database().ref(path).on('value', snapshot => {
IDOfUserToKill = '';
if (snapshot.val()) {
IDOfUserToKill = snapshot.val().userToKill;
console.log(IDOfUserToKill); // return the good ID
}
});
}
userID = IDOfUserToKill; // return "tralala" and not the good ID
Then I want to use the variable IDOfUserToKill outside this one. Because if I use IDOfUserToKill, it returns the value that was defined before the function (tralala) and not the ID.
How to retrieve the content of the variable? (I use React Native).
This function:
fb.database().ref(path).on('value', snapshot => {
IDOfUserToKill = '';
if (snapshot.val()) {
IDOfUserToKill = snapshot.val().userToKill;
console.log(IDOfUserToKill); // return the good ID
}
});
is asynchronous which means it moves on to another task before it finishes.
That is why inside on() you get the id that is in the database, while outside, here userID = IDOfUserToKill; you get the value 'tralala'.
To learn more about asychronous check this:
https://medium.com/google-developers/why-are-firebase-apis-asynchronous-callbacks-promises-tasks-e037a6654a93

Categories