This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I want to get a "value of Data" from Firebase Realtime Database. You can find my code below:
async function getName() {
const result = await firebase.database().ref('/users/' + user.user.uid)
.once('value').
then(async function(snapshot) {
console.log("SNapshot =>");
console.log(snapshot.val().displayName); // returns "John Doe"
const result2 = await snapshot.val().displayName;
return result2;
});
return result; // returns "Promise Object"
};
It returns "Promise". But i want to get value not promise.
How should i fix my code?
Thanks.
You are mixing up use of async/await with then()/catch(). You should pick one syntax or the other, not both together in this case. You are also trying to use await on something that is not a promise. Just write your function like this:
async function getName() {
const snapshot = await firebase.database().ref('/users/' + user.user.uid).once('value')
return snapshot.val().displayName
}
And call it like this:
const name = await getName()
The getname function is doing async operation so you can do:
try {
await result = getName();
} catch (e) {
throw e;
}
within an async function, or, if you prefer without async :
result.then((res) => console.log(res));
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
async/await implicitly returns promise?
(5 answers)
Closed 2 years ago.
Get the value from a function in some other languages is simple like write return something
I can't get how to do it in JS from an async function.
const URL = `https://www.reddit.com/r/all.json`;
async function getPost() {
var list = [];
let response = await fetch(URL).then((res) => res.json());
let childList = await response.data.children;
childList.map((el) => {
let id = el.data.id;
let title = el.data.title;
list.push({
id: id,
title: title,
});
});
console.log(list);
}
var oo = getPost();
If you try the code like this everything work fine. But if to change console.log(list) inside getPOst() to return list and try to console.log(oo) nothing is showing
So... BIG thanks to #nick-parsons
that's the answer:
Oh, so a Promise is being shown. Your async function will wrap the >return value in a Promise, so that's expected. To "extract" the >value/list, you need to use .then(list => // use list here) on the >returned Promise. Or, if you're in a ES module, you can await the >Promise
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I make calendar for my project and need to use seved data from server inside "function CalendarPicker()".
I get data from server as promise and try use it inside "function CalendarPicker()" but always get undefined. How can I force it?
async function _getMeetingsData() {
let response = await fetch('calendar');
let data = await response.json();
data = JSON.stringify(data);
return data;
}
function CalendarPicker() {
//Get meeting data
this.meetingsData = _getMeetingsData();
this._insertNavigationButtons();
this._insertHeaderIntoCalendarWrapper();
this._insertCalendarGridDaysHeader();
this._insertDaysIntoGrid();
this._insertCalendarIntoWrapper();
}
const myCalender = new CalendarPicker();
You need to have an async constructor (arguably odd) or await for your data, because every async function is implicitly a promise, even if it synchronously returns a value ... so:
function CalendarPicker() {
//Get meeting data ... then
_getMeetingsData().then(meetingsData => {
this.meetingsData = meetingsData;
this._insertNavigationButtons();
this._insertHeaderIntoCalendarWrapper();
this._insertCalendarGridDaysHeader();
this._insertDaysIntoGrid();
this._insertCalendarIntoWrapper();
});
}
This works, but if you have any prototype method that needs that data, you better store the promise:
function CalendarPicker() {
//Get meeting data ... then
this._meetingsData = _getMeetingsData().then(meetingsData => {
this.meetingsData = meetingsData;
this._insertNavigationButtons();
this._insertHeaderIntoCalendarWrapper();
this._insertCalendarGridDaysHeader();
this._insertDaysIntoGrid();
this._insertCalendarIntoWrapper();
});
}
CalendarPicker.prototype.doThings = function () {
this._meetingsData.then(() => {
console.log(this.meetingsData);
});
};
Because you have defined _getMeetingsData as an async function, you need to call _getMeetingsData with the await keyword. In that case, you also need to make CalendarPicker an async function. Alternatively, you can call _getMeetingsData within a promise construct in your CalendarPicker function.
This question already has an answer here:
js async/await return promise
(1 answer)
Closed 4 years ago.
Here's the function:
const getUserIP = async () => {
let response = await fetch('https://jsonip.com/');
let json = await response.json();
console.log(json.ip)
return json.ip;
};
In the console, the IP address is logged as expected. However, when I save the 'IP address' to a variable:
const ip = getUserIP();
And then type ip in the console, the value is shown as:
Promise { <state>: "fulfilled", <value>: "/* my IP here*/" }
I've watched videos on YouTube who have used the same logic/syntax albeit for a different API, but it works. I've searched Google and SO and couldn't find a thread with the same issue.
What am I missing?
Thanks.
Async functions return Promises, you need to get that value as follow:
getUserIP().then(ip => console.log(ip)).catch(err => console.log(err));
Or, you can add the async declaration to the main function who calls the function getUserIP:
async function main() {
const ip = await getUserIP();
}
async functions return a Promise, and its resolved value is whatever you return from it. To get ip, you must use then.
getUserIP().then(ip => {})
You have to add .then to getUserIP() because async function is returning a promise.
getUserIp().then(ip => console.log(ip));
You can also
(async() => {
const ip = await getUserIP();
console.log(ip);
})();
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I got this code using the async/await :
function _getSSID(){
return new Promise((resolve, reject)=>{
NetworkInfo.getSSID(ssid => resolve(ssid))
})
}
async function getSSID(){
let mySSID = await _getSSID()
if (mySSID == "error") {
return 'The value I want to return'
}
}
And getSSID() is equal to this :
Looks like the getSSID() function will always return a promise. How can I get "The value I want to return" in plain text ?
Any help is greatly appreciated.
Declaring a function async means that it will return the Promise. To turn the Promise into a value, you have two options.
The "normal" option is to use then() on it:
getSSID().then(value => console.log(value));
You can also use await on the function:
const value = await getSSID();
The catch with using await is it too must be inside of an async function.
At some point, you'll have something at the top level, which can either use the first option, or can be a self-calling function like this:
((async () => {
const value = await getSSID();
console.log(value);
})()).catch(console.error):
If you go with that, be sure to have a catch() on that function to catch any otherwise uncaught exceptions.
You can't use await at the top-level.
This question already has answers here:
Async function returning promise, instead of value
(3 answers)
Closed 1 year ago.
Trying to get familiar with async/await, I've tried the following code in Chrome:
async function f() {
return await $.get('/');
};
var result = f();
but result doesn't hold the result (string); rather it holds a Promise which needs to be awaited again. This code does give me the response string:
var response = await $.get('/');
How can I return the actual response string from a function using await?
either
function f() {
return $.get('/');
};
async test() {
var x = await f()
console.log(x)
}
test()
or
f().then(function(res) {
console.log(res)
}
the async/await is just another way to write the same logic.
await and async are basically just syntactical sugar on top of Promise. If you end up with a Promise at the end, you still need to treat it like a Promise.
const response = f().then(() => { });
Or, if you are calling it inside of an async function, you can await to resolve it:
async function main() {
const response = await f();
console.log(response);
}
A pattern I like to use is have my main code wrapped in a self-executing async function, so I can still use await:
(async () => {
const result = await doSomething();
console.log(result);
})();
Note that even with that pattern, I need a final catch() to catch any errors it may have that aren't caught otherwise:
(async () => {
// blah blah
})().catch(() => {});
The return type of async functions is Promise. So you will have to await or then() to get the result.