Return value read Firebase database - node.js

I am making a function in nodejs to read a value from the database in Firebase and return it. I read in the that way and get the right value by the console.log(), but when i made the return of the value doesn´t work properly when i call that function
function test() {
database.ref(sessionId + '/name/').once("value").then((snapshot) => {
var name = snapshot.child("respuesta").val()
console.log(name);
return name;
});
}
If someone could help me. Thanks

You're not returning anything from test, so undefined is being implicitly returned. You can return the promise like this:
function test() {
return database.ref(// everything else is identical
}
Note that this will be returning a promise that resolves to the name, not the name itself. It's impossible to return the name, because that doesn't exist yet. To interact with the eventual value of the promise, you can call .then on the promise:
test().then(name => {
// Put your code that uses the name here
})
Or you can put your code in an async function and await the promise:
async function someFunction() {
const name = await test();
// Put your code that uses the name here
}

Related

how to get [chrome.instanceID.getID] , [chrome.storage.sync.get] by async & await?

How do you get the information for the Chrome extension by using async and await?
[chrome.instanceID.getID]
[chrome.storage.sync.get]
We tried this code:
async function test()
{
let _r = await chrome.instanceID.getID();
return _r;
}
let _pc_id = test();
but _pc_id returns a promise. We find no way to get the value in it. How should we do this?
You can get the instanceID like this, but can't store it in a variable to use it out of scope of the promise, AFAIK. You may want to read this: saving data from promise in a variable
If you want to use the returned value of Promise you need to do it in the promise or in .then()s after the promise, at least that is how I do it.
chrome.instanceID.getID example:
chrome.instanceID.getID((instance_id) => {
console.log(instance_id);
// Execute your other related code here
});
or
var promise = chrome.instanceID.getID();
promise.then((instance_id) => {
console.log(instance_id);
// Execute your other related code here
});
or
chrome.instanceID.getID()
.then((instance_id) => {
console.log(instance_id);
// Execute your other related code here
});
chrome.storage.sync.get example:
chrome.storage.sync.get('myKey', function(items) {
var key = items.myKey;
// Below code is an example, change it to your needs
if (key) {
console.log(key)
} else {
key = createKey(); // a custom function that generates keys
chrome.storage.sync.set({myKey: key}, function () {
console.log(key);
});
}
};

NodeJS Fetch Return always returns undefined

I'm trying to return a variable via a API, but when I go to return it, it always returns it as undefined
There is the function:
function getCityName()
{
console.log("Trying to return city location...");
var url = util.format('https://api.truckyapp.com/v2/map/%s/resolve?x=%s&y=%s', game.game.name, data.position.X, data.position.Y);
fetch(url).then(function(data) {
return data.json();
}).then(function(parsed){
return parsed.response.poi.realName;
});
}
Code to run the function:
var city = getCityName();
console.log("City name is: "+city)
INFO: The JSON shows correctly
You would need to return the final value returned by the callback from the getCityName function:
function getCityName()
{
console.log("Trying to return city location...");
var url = util.format('https://api.truckyapp.com/v2/map/%s/resolve?x=%s&y=%s', game.game.name, data.position.X, data.position.Y);
return fetch(url).then(function(data) {
return data.json();
}).then(function(parsed){
return parsed.response.poi.realName;
});
}
The above would cause getCityName to return a Promise. To get the actual value of the city, you would now have to wait for the Promise to resolve (using either await or then). Going by the standard followed, it would be:
getCityName().then(city => {
console.log("City name is: "+city);
});
Just to add, since getCityName would returning a Promise which might reject, it would be sensible to add a catch block while calling the function as well.

How to fix - Promise { <pending> } in Node.js and use it as variable anywhere

I'm accessing google API for converting coordinates into detailed objects using node-geocoder library from npmjs. Everything went well and I'm getting the expected object from geocoder API. The problem started the moment when I thought of using the data outside the promise function. I want to use the values outside the promise/async-await function.
Below is the code I've tried, Pls take a look and help me. TIA...
function goecoderPromiseFunction() {
return new Promise(function (resolve, reject) {
geocoder.reverse({ lat: 45.767, lon: 4.833 })
.then(data => {
cityName = data[0].city;
resolve(cityName);
})
.catch(err => {
console.log(err);
});
});
}
async function app() {
var a = await goecoderPromiseFunction();
return a;
}
var a = app();
console.log("a->", a);
I expect the variable "a" should print the city name "Lyon", but it prints
a-> Promise { < pending > }
The promise returned by the app function is never consumed, that is why it remains in a pending state.
Call then on the app function to get the result :
app().then(a => console.log("a->", a));
You can also use async/await :
(async function() {
var a = await app();
console.log("a->", a);
})();
An asynchronous function actually returns a promise that 'resolves' to the function's return value. You are therefore assigning a promise to the value of a. If you are in the global scope, you obviously cannot use async/await so you need to use either a self-executing async function or you need to run
a.then(data => console.log('a->', data));
to get what you are looking for.
Find out more about async functions here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
It prints because console.log("a->", a); runs while promise haven't returned answer for a variable "a"
Note: you haven't used reject function, if there is an error you wont notice and may be that error was the required answer to be carried by variable "a" that's why it still pending i.e still waiting.
For more idea try to use reject function inside the catch block example reject(err)
instead of console it out as you've done

shopify-api-node: promise not returning value

Setting up a node.js app to retrieve order(s) information from shopify. I'm trying to store that data and run some logic, but I can't seem to get a hold of it.
THIS WORKS:
shopify.order.list()
.then(function(orders){
console.log(orders);
});
THIS DOES NOT WORK:
var orders_json;
shopify.order.list()
.then(function(orders){
orders_json=orders;
//console.log(orders);
});
console.log(orders_json); //returns undefined
Let me introduce you to the world of async/await. As long as you declare your function as async and the function you are "awaiting" returns a promise, you can handle this in a more synchronous way. Have a look at the docs linked above. Notice how I called the async function after it was declared. You can't call await outside the scope of an async function.
async function fetchOrders() {
try {
const orders_json = await shopify.order.list();
// do stuff with orders_json
return orders_json;
} catch(err) {
// handle err
}
}
const orders = fetchOrders();

How to use result of a function that uses promises

I have a function,
asdf() {
var a = fooController.getOrCreateFooByBar(param);
console.log("tryna do thing");
console.log(a); //undefined
if (!a.property) {
//blah
}
that dies. getOrCreateFooByBar does a
Model.find({phoneNumber : number}).exec()
.then(function(users) {})
and finds or creates the model, returning it at the end:
.then(function(foo) { return foo}
How can I use the result of this in asdf()? I feel like this is a fairly easy question but I am getting stuck. If I try to do a.exec() or a.then() I get 'a cannot read property of undefined' error.
The main idea about Promises (as opposed to passed callbacks) is that they are actual objects you can pass around and return.
fooController.getOrCreateFooByBar would need to return the Promise it gets from Model.find() (after all of the processing done on it). Then, you'll be able to access it in a in your asdf function.
In turn, asdf() should also return a Promise, which would make asdf() thenable as well. As long as you keep returning Promises from asynchronous functions, you can keep chaining them.
// mock, you should use the real one
const Model = { find() { return Promise.resolve('foo'); } };
function badExample() {
Model.find().then(value => doStuff(value));
}
function goodExample() {
return Model.find().then(value => doStuff(value));
}
function asdf() {
var a = badExample();
var b = goodExample();
// a.then(whatever); // error, a is undefined because badExample doesn't return anything
return b.then(whatever); // works, and asdf can be chained because it returns a promise!
}
asdf().then(valueAfterWhatever => doStuff(valueAfterWhatever));

Resources