Handling Async Function - javascript

I have the following function:
export function readUserData(userName, password) {
firebase.database().ref("users/" + userName).once("value").then(function (snap) {
//console.log(snap.val().salt);
var verification = passwordVerify(password, snap.val().salt);
//console.log(verification);
//console.log(snap.val().password);
console.log(snap.val());
return snap.exists() && snap.val().password === verification
? userAuth.located = snap.val()
: userAuth.located = false;
});
return userAuth.located;
}
I am told that firebase.database().ref is an asynchronous function, and it seems to be so in that it returns userAuth.located in the final line of readUserData before writing console.log(snap.val());
How do I ensure that firebase.database().ref... executes before I return the final result? I am unsure how to implement await/promises into this code as the overall function is not asynchronous.

You should return the promise, like:
export function readUserData(userName, password) {
return firebase.database().ref("users/" + userName)
.once("value")
.then(function (snap) {
var verification = passwordVerify(password, snap.val().salt);
return snap.exists() && snap.val().password === verification
? snap.val()
: false;
});
}
Then, whichever code calls this method, should also async-await:
var userAuthLocated = await readUserData(userName, password);
or, with promises:
readUserData(userName, password)
.then(userAuthLocated => {
// use userAuthLocated here
});

To address your comment above #Seaphin. There is one more step needed with the following line
var userAuthLocated = await readUserData(userName, password);
What is happening is that your app is using userAuthLocated before it updates. userAuthLocated does get updated by the firebase call in readUserData, however, you are missing an async() function.
Using await should always be wrapped in an async () function call. It should look something similar to this
userAuth = async () => {
var userAuthLocated = await readUserData(userName, password);
//setstate or
return userAuthLocated
Essentially using async "blocks" until the value is ready to use. Functions waiting on that value won't execute until the async function unblocks

Related

Await Not Working With Firebase Firestore Calls Javascript [duplicate]

I wrote this code in lib/helper.js:
var myfunction = async function(x,y) {
....
return [variableA, variableB]
}
exports.myfunction = myfunction;
Then I tried to use it in another file :
var helper = require('./helper.js');
var start = function(a,b){
....
const result = await helper.myfunction('test','test');
}
exports.start = start;
I got an error:
await is only valid in async function
What is the issue?
The error is not refering to myfunction but to start.
async function start() {
....
const result = await helper.myfunction('test', 'test');
}
// My function
const myfunction = async function(x, y) {
return [
x,
y,
];
}
// Start function
const start = async function(a, b) {
const result = await myfunction('test', 'test');
console.log(result);
}
// Call start
start();
I use the opportunity of this question to advise you about an known anti pattern using await which is : return await.
WRONG
async function myfunction() {
console.log('Inside of myfunction');
}
// Here we wait for the myfunction to finish
// and then returns a promise that'll be waited for aswell
// It's useless to wait the myfunction to finish before to return
// we can simply returns a promise that will be resolved later
// useless async here
async function start() {
// useless await here
return await myfunction();
}
// Call start
(async() => {
console.log('before start');
await start();
console.log('after start');
})();
CORRECT
async function myfunction() {
console.log('Inside of myfunction');
}
// Here we wait for the myfunction to finish
// and then returns a promise that'll be waited for aswell
// It's useless to wait the myfunction to finish before to return
// we can simply returns a promise that will be resolved later
// Also point that we don't use async keyword on the function because
// we can simply returns the promise returned by myfunction
function start() {
return myfunction();
}
// Call start
(async() => {
console.log('before start');
await start();
console.log('after start');
})();
Also, know that there is a special case where return await is correct and important : (using try/catch)
Are there performance concerns with `return await`?
To use await, its executing context needs to be async in nature
As it said, you need to define the nature of your executing context where you are willing to await a task before anything.
Just put async before the fn declaration in which your async task will execute.
var start = async function(a, b) {
// Your async task will execute with await
await foo()
console.log('I will execute after foo get either resolved/rejected')
}
Explanation:
In your question, you are importing a method which is asynchronous in nature and will execute in parallel. But where you are trying to execute that async method is inside a different execution context which you need to define async to use await.
var helper = require('./helper.js');
var start = async function(a,b){
....
const result = await helper.myfunction('test','test');
}
exports.start = start;
Wondering what's going under the hood
await consumes promise/future / task-returning methods/functions and async marks a method/function as capable of using await.
Also if you are familiar with promises, await is actually doing the same process of promise/resolve. Creating a chain of promise and executes your next task in resolve callback.
For more info you can refer to MDN DOCS.
When I got this error, it turned out I had a call to the map function inside my "async" function, so this error message was actually referring to the map function not being marked as "async". I got around this issue by taking the "await" call out of the map function and coming up with some other way of getting the expected behavior.
var myfunction = async function(x,y) {
....
someArray.map(someVariable => { // <- This was the function giving the error
return await someFunction(someVariable);
});
}
I had the same problem and the following block of code was giving the same error message:
repositories.forEach( repo => {
const commits = await getCommits(repo);
displayCommit(commits);
});
The problem is that the method getCommits() was async but I was passing it the argument repo which was also produced by a Promise. So, I had to add the word async to it like this: async(repo) and it started working:
repositories.forEach( async(repo) => {
const commits = await getCommits(repo);
displayCommit(commits);
});
If you are writing a Chrome Extension and you get this error for your code at root, you can fix it using the following "workaround":
async function run() {
// Your async code here
const beers = await fetch("https://api.punkapi.com/v2/beers");
}
run();
Basically you have to wrap your async code in an async function and then call the function without awaiting it.
The current implementation of async / await only supports the await keyword inside of async functions Change your start function signature so you can use await inside start.
var start = async function(a, b) {
}
For those interested, the proposal for top-level await is currently in Stage 2: https://github.com/tc39/proposal-top-level-await
async/await is the mechanism of handling promise, two ways we can do it
functionWhichReturnsPromise()
.then(result => {
console.log(result);
})
.cathc(err => {
console.log(result);
});
or we can use await to wait for the promise to full-filed it first, which means either it is rejected or resolved.
Now if we want to use await (waiting for a promise to fulfil) inside a function, it's mandatory that the container function must be an async function because we are waiting for a promise to fulfiled asynchronously || make sense right?.
async function getRecipesAw(){
const IDs = await getIds; // returns promise
const recipe = await getRecipe(IDs[2]); // returns promise
return recipe; // returning a promise
}
getRecipesAw().then(result=>{
console.log(result);
}).catch(error=>{
console.log(error);
});
If you have called async function inside foreach update it to for loop
Found the code below in this nice article: HTTP requests in Node using Axios
const axios = require('axios')
const getBreeds = async () => {
try {
return await axios.get('https://dog.ceo/api/breeds/list/all')
} catch (error) {
console.error(error)
}
}
const countBreeds = async () => {
const breeds = await getBreeds()
if (breeds.data.message) {
console.log(`Got ${Object.entries(breeds.data.message).length} breeds`)
}
}
countBreeds()
Or using Promise:
const axios = require('axios')
const getBreeds = () => {
try {
return axios.get('https://dog.ceo/api/breeds/list/all')
} catch (error) {
console.error(error)
}
}
const countBreeds = async () => {
const breeds = getBreeds()
.then(response => {
if (response.data.message) {
console.log(
`Got ${Object.entries(response.data.message).length} breeds`
)
}
})
.catch(error => {
console.log(error)
})
}
countBreeds()
In later nodejs (>=14), top await is allowed with { "type": "module" } specified in package.json or with file extension .mjs.
https://www.stefanjudis.com/today-i-learned/top-level-await-is-available-in-node-js-modules/
This in one file works..
Looks like await only is applied to the local function which has to be async..
I also am struggling now with a more complex structure and in between different files. That's why I made this small test code.
edit: i forgot to say that I'm working with node.js.. sry. I don't have a clear question. Just thought it could be helpful with the discussion..
function helper(callback){
function doA(){
var array = ["a ","b ","c "];
var alphabet = "";
return new Promise(function (resolve, reject) {
array.forEach(function(key,index){
alphabet += key;
if (index == array.length - 1){
resolve(alphabet);
};
});
});
};
function doB(){
var a = "well done!";
return a;
};
async function make() {
var alphabet = await doA();
var appreciate = doB();
callback(alphabet+appreciate);
};
make();
};
helper(function(message){
console.log(message);
});
A common problem in Express:
The warning can refer to the function, or where you call it.
Express items tend to look like this:
app.post('/foo', ensureLoggedIn("/join"), (req, res) => {
const facts = await db.lookup(something)
res.redirect('/')
})
Notice the => arrow function syntax for the function.
The problem is NOT actually in the db.lookup call, but right here in the Express item.
Needs to be:
app.post('/foo', ensureLoggedIn("/join"), async function (req, res) {
const facts = await db.lookup(something)
res.redirect('/')
})
Basically, nix the => and add async function .
"await is only valid in async function"
But why? 'await' explicitly turns an async call into a synchronous call, and therefore the caller cannot be async (or asyncable) - at least, not because of the call being made at 'await'.
Yes, await / async was a great concept, but the implementation is completely broken.
For whatever reason, the await keyword has been implemented such that it can only be used within an async method. This is in fact a bug, though you will not see it referred to as such anywhere but right here. The fix for this bug would be to implement the await keyword such that it can only be used TO CALL an async function, regardless of whether the calling function is itself synchronous or asynchronous.
Due to this bug, if you use await to call a real asynchronous function somewhere in your code, then ALL of your functions must be marked as async and ALL of your function calls must use await.
This essentially means that you must add the overhead of promises to all of the functions in your entire application, most of which are not and never will be asynchronous.
If you actually think about it, using await in a function should require the function containing the await keyword TO NOT BE ASYNC - this is because the await keyword is going to pause processing in the function where the await keyword is found. If processing in that function is paused, then it is definitely NOT asynchronous.
So, to the developers of javascript and ECMAScript - please fix the await/async implementation as follows...
await can only be used to CALL async functions.
await can appear in any kind of function, synchronous or asynchronous.
Change the error message from "await is only valid in async function" to "await can only be used to call async functions".

Async Function Inside Async Function

I am trying to get Data over my API-Endpoint and want to populate my page with the data.
I know that I have to use async/await to be sure that the variable was filled. Therefore I wrote the following lines and want to know that it is possible to write an async function inside an async function. It is working but I am not sure if it is the correct way:
async function getRoom(id) {
const response = await fetch('/api/zimmer/' + id);
if (!response.ok) {
const message = `An error has occured: ${response.status}`;
throw new Error(message);
}
const rooms = await response.json();
console.log(rooms);
return rooms;
}
async function getSelectedItem() {
var e = document.getElementById("Objekt");
if (e.value > 0) {
zimmer_select.disabled = false;
var response = await getRoom(e.value);
console.log(response);
response.forEach(function(element) {
console.log(element);
});
} else {
zimmer_select.disabled = true;
}
console.log(e.value);
}
I think it is fine to use it this way actually.
If you think about, sometimes you have to use async inside async. What if you have some async function which fetches data and you have to loop over that data and await for something. If you loop it with for each you won't be able to use await, so you should put async before it. So as long it's clean and have no other way, I think it is fine to use async inside async.

Nodejs async/await not working as expected

I have an express API that reads from my fauna database. I have a class setup called Database that handles all my fauna queries, and an async method called getQuotes that essentially gets a fauna document, the general structure is like this:
async getQuotes() {
// note, `query` is an async function
const doc = this.client.query(...).then((res) => {
const data = ...; // to keep this short I'm not gonna show this
console.log("faunadb handler: " + data); // just for debug
return Promise.resolve(data);
})
}
Then when I start the express API, I have it call the getQuotes method and log the data (just for debug).
const quotes = db.getQuotes().then((quotes) => {
console.log("fauna consumer: " + quotes);
})
Now, when I run the app, I get the following output:
starting server on port.... ussual stuff
fauna consumer: undefined
faunadb handler: { ... }
The fauna consumer code runs before we actually get the promise from the fauna query API. I need to use .then because node for some reason doesn't allow me to use await. Does anyone know how to solve this? Thank you!
(using node version v16.14.0, running on Arch Linux)
You aren't returning anything from your getQuotes() function. The return in your callback is only going to return from the callback, not from the enclosing function. You also aren't awaiting anywhere, which means your async function is not going to actual wait on the result of your query.
try to use await
async getQuotes() {
const res = await this.client.query(...);
const data = ...;
console.log("faunadb handler: " + data); // just for debug
return data;
}
// must be in async function
const quotes = await db.getQuotes();
console.log("fauna consumer: " + quotes);
The problem is that you need to return data fromgetQuotesPlease just change the code as follows (replace the placeholders):
async getQuotes() {
// note, `query` is an async function
const res = await this.client.query(...)
const data = ...; // to keep this short I'm not gonna show this
console.log("faunadb handler: " + data); // just for debug
return data
}
getQuotes function should return the result like this.
async getQuotes() {
// note, `query` is an async function
return this.client.query(...).then((res) => {
const data = ...; // to keep this short I'm not gonna show this
console.log("faunadb handler: " + data); // just for debug
return Promise.resolve(data);
})
}
or
async getQuotes() {
// note, `query` is an async function
const doc = await this.client.query(...);
const data = ...; // to keep this short I'm not gonna show this
console.log("faunadb handler: " + data); // just for debug
return Promise.resolve(data);
}
From my perspective it's better not to mix up await and then. Either use one or another.
I'd recommend to go with await.
async getQuotes() {
// note, `query` is an async function
const res = await this.client.query(...)
const doc = ...; // to keep this short I'm not gonna show this
console.log("faunadb handler: " + doc); // just for debug
return doc;
}

Await isn't waiting?

Hi I've got two functions. They're called inside another function. And I need the second function execute after the first is done.
I'm sorry this is probably a very simple question, but I'm still trying to wrap my head around promises and async/await in js. Can anyone help me figure out why this isn't working.
async function addDetails(){
const sub = await getSession();
// now wait for firstFunction to finish...
addProfileDetails(sub);
};
I have debug/logging statements in both. So I know that addProfileDetails is being executed before the variable sub is defined.
I'm using react native and node.js
EDIT:
export function getSession() {
console.log("checking user ...............................................")
Auth.currentSession().then(res=>{
console.log("retrieving token");
let accessToken = res.getAccessToken()
let payload = accessToken.payload;
console.log(`sub: ${payload.sub}`)
return payload.sub
})
};
This is my getSession() function. It also needs to be async?
You must return a promise from the function that you want to await
export function getSession() {
console.log("checking user ...............................................")
return Auth.currentSession().then(res=>{
console.log("retrieving token");
let accessToken = res.getAccessToken()
let payload = accessToken.payload;
console.log(`sub: ${payload.sub}`)
return payload.sub
})
};
Try this in your getSession
export function getSession() {
return new Promise((resolve, reject) => {
console.log("checking user ...............................................")
Auth.currentSession().then(res=>{
console.log("retrieving token");
let accessToken = res.getAccessToken()
let payload = accessToken.payload;
console.log(`sub: ${payload.sub}`)
resolve(payload.sub)
})
};

How to wait for a Firebase retrieve value and only then exit the function?

I have a Firebase query.
Because Firebase works asynchronously, the function continue to run without waiting for the Firebase retrieve value.
Is there a way to wait for the result from the Firebase query and only then to make the return from the function?
function CheckBuyingCondition(prefix){
var Res= "";
var Current_Price_Open_ref = firebase.database().ref("dailyT/Current_Price_Open/"+nextDayTrading).orderByChild("Prefix").equalTo(prefix)
Current_Price_Open_ref.once("value").then(function(snapshot) {
if(snapshot.exists()){
snapshot.forEach(function(childSnapshot) {
var val = childSnapshot.val();
res =""+ val.Current_Price_Open;
});
}else{
res = "NA";
}
});
return res; //(Here i got res = "" instead of the correct value from Firebase query
}
Use async/await:
async function checkBuyingCondition(prefix) {
var res = '';
var currentPriceOpenRef = firebase.database()
.ref(`dailyT/currentPriceOpen/${nextDayTrading}`)
.orderByChild('prefix')
.equalTo(prefix);
var snapshot = await currentPriceOpenRef.once('value');
if(snapshot.exists()) {
snapshot.forEach(function(childSnapshot) {
var val = childSnapshot.val();
res = `${val.currentPriceOpen}`;
});
} else {
res = 'NA';
}
return res;
}
Take note that this does not make your function synchronous at all, thus the async keyword at the beginning of your function declaration; it just makes your function look like one.
On the 3rd line inside the function you'll notice the await keyword. This waits for your promise to resolve then returns the result which in your case, is the snapshot from Firebase. You can only use await inside async functions.
More Reading: Javascript Async/Await
What you're proposing is making the Firebase SDK asynchronous call into an synchronous call. This is not a good idea, and to be honest, not even possible in JavaScript. If you need to make a helper function that deals with Firebase APIs, that function should instead accept a callback function to be invoked when the work completes, or return a promise so that the caller of the function can decide what to do next.
Read here to learn more about why Firebase APIs are asynchronous.
Try this:
function CheckBuyingCondition(prefix){
var Res= "";
var Current_Price_Open_ref = firebase.database().ref("dailyT/Current_Price_Open/"+nextDayTrading).orderByChild("Prefix").equalTo(prefix)
return Current_Price_Open_ref.once("value").then(function(snapshot) {
if(snapshot.exists()){
snapshot.forEach(function(childSnapshot) {
var val = childSnapshot.val();
res =""+ val.Current_Price_Open;
});
return res;
}else{
res = "NA";
}
});
}
Firebase queries are promises, so you because you can return the result from the promise and get it with another promise.

Categories

Resources