it passes the object to the function but I don't know why, despite the fact that it is visible there, I cannot return individual elements of this object because it shows "undefined" in the console logs. Anyone have any idea what I should do or am I doing wrong?
Code:
async function getMonitors(){
try {
let res = await fetch(API_URL+"/"+API_VERSION+"/status/monitors/"+location.hostname+"/list");
var data = await res.json();
if(data.success){
delete data.success;
return data;
}else{
e=data.message;
}
} catch(error){
e=error;
}
if(typeof e!="undefined"&&e!==null){system.error(e);}
}
function getMonitorsData(data){
let totalMonitors = data.totalMonitors;
console.log(data);
}
var m = getMonitors();
var data = getMonitorsData(m);
Screen of the returned object in the function Object
You have missed await keyword while calling getMonitors() function.
async function getMonitors(){
try {
let res = await fetch(API_URL+"/"+API_VERSION+"/status/monitors/"+location.hostname+"/list");
var data = await res.json();
if(data.success){
delete data.success;
return data;
}else{
e=data.message;
}
} catch(error){
e=error;
}
if(typeof e!="undefined"&&e!==null){system.error(e);}
}
function getMonitorsData(data){
let totalMonitors = data.totalMonitors;
console.log(data);
}
async function init() {
var m = await getMonitors();
var data = getMonitorsData(m);
}
init();
you have forgotten to call the function and pass the data that are response from your API
async function getMonitors(){
try {
let res = await fetch("https://www.7timer.info/bin/astro.php?lon=113.2&lat=23.1&ac=0&unit=metric&output=json&tzshift=0");
var data = await res.json();
getMonitorsData(data) // here is what i added for passing response to function
if(data.success){
delete data.success;
return data;
}else{
e=data.message;
}
} catch(error){
e=error;
}
if(typeof e!="undefined"&&e!==null){system.error(e);}
}
function getMonitorsData(data){
let totalMonitors = data.totalMonitors;
console.log(data);
}
var m = getMonitors();
var data = getMonitorsData(m);
Related
I'm trying to create an object which when any properties are set would update its corresponding indexedDB data automatically.
The following code works as intended but each time that I'm calling the object from the indexedb. I need to create the object as
new
ResultsModel(indexedDbData._scores,indexedDbData._overallScore,indexedDbData.id)
Which seems an "anti-pattern" as I'm calling what would be "private" variables even if at this point it's just data.
Is that an issue?
I'm also not sure about setting up "setter" and "getter" ? Should I just create "update" function at this point ?
What would be a good pattern to achieve this ?
export class ResultsModel{
constructor(scores,overallScore, id){
this._scores = scores;
this._overallScore = overallScore;
this.id = id;
}
async init(){
sessionStorage.setItem("lastResults", JSON.stringify(this));
await this.save();
}
async save(){
let req = await db.transaction("moodResults","readwrite").objectStore("moodResults").put(this);
req.onsuccess = function(event) {console.log("saved")}
req.onerror = function(event) {console.log("error")}
}
get scores(){
return this._scores;
}
get overallScore(){
return this._overallScore;
}
set scores(newValue){
this._scores = newValue;
}
set overallScore(newValue){
this._overallScore = newValue;
if(this.overallScore === undefined){return}
return (async () =>{
let objectStore = await db.transaction("moodResults","readwrite").objectStore("moodResults");
const req = await objectStore.get(parseInt(this.id));
req.onsuccess = async () =>{
if(req.result === undefined){
throw new Error("Object with specified key not found");
}
const data = req.result;
data._overallScore = newValue;
const updateOverallScore = objectStore.put(data)
updateOverallScore.onsuccess = () =>{
console.log("update worked")
}
updateOverallScore.onerror = () =>{
console.log("update didn't worked")
}
}
req.onerror = () =>{
console.log("getting object didn't work")
}
})()
}
}
I code this to get a JSON array from my sever
var students_list;
const library_address = 'http://localhost:17330'
async function data(a,b) {
if(a == 'getdata')
{
const respone = await fetch(library_address + `/${a}/${b}`);
const output = await respone.json();
console.log(output);
return output;
}
}
But the problem is I can't get the array outside of that function, the result give me a promise object instead
students_list = data('getdata','student') //promise
var students_list;
const library_address = 'http://localhost:17330'
async function data(a,b) {
if(a == 'getdata')
{
const respone = await fetch(library_address + `/${a}/${b}`);
const output = respone.json(); // just delete await
console.log(output);
return output;
}
}
Once you use async, response will be a Promise object. You need use await to get what you want.
async function getDNShomeIP(){
var response = await fetch('https://dns.google/resolve?name=example.com'); // this uses the google api
var json = await response.json();
var homeIPadress = json.Answer[0].data;
console.log(homeIPadress);
return homeIPadress;
};
async function getCurrentIP(){
var response = await fetch("https://api.ipify.org?format=json");
var json = await response.json()
var currentIPadress = json.ip;
return currentIPadress;
}
var homeIPadress = getDNShomeIP();
var currentIPadress = getCurrentIP();
if (homeIPadress == currentIPadress){
alert("from same from lol");
} else {
alert("not from same")
};
Hi there,
I wanted to know how to compare the values of two promises in Javascript.
I can't work out how to make the program wait before the if statement.
The statement just evaluates to false if the promises are not yet fulfilled so program follows the else branch.
Thanks
Use the "await" keyword inside another "async" function so that the function waits for a response before it continues execution.
async function testEquality() {
var homeIPadress = await getDNShomeIP();
var currentIPadress = await getCurrentIP();
if (homeIPadress === currentIPadress) {
alert("from same from lol");
} else {
alert("not from same")
};
}
testEquality();
I would also recommend you use triple equal (===) to compare the results as this uses strict equality comparison.
You could wrap it in another async function:
async function execute() {
var homeIPadress = await getDNShomeIP();
var currentIPadress = await getCurrentIP();
if (homeIPadress == currentIPadress){
alert("from same from lol");
} else {
alert("not from same");
}
}
execute();
first you need to fix your fetch function, then fix the async await function
you have to put your await function on async function just like this,
fix your getdnshomeip just like the code below
function getCurrentIP(){
return fetch("https://api.ipify.org?format=json")
.then( r => r.json())
.then( r => r);
}
const check = async () => {
var currentIPadress = await getCurrentIP();
var homeIPadress = await getDNShomeIP();
if (homeIPadress === currentIPadress){
alert("from same from lol");
} else {
alert("not from same")
};
}
check();
You're describing a function I created
async function getDNShomeIP(){
var response = await fetch('https://dns.google/resolve?name=example.com');
var json = await response.json();
var homeIPadress = json.Answer[0].data;
console.log(homeIPadress);
return homeIPadress;
};
async function getCurrentIP(){
var response = await fetch("https://api.ipify.org?format=json");
var json = await response.json()
var currentIPadress = json.ip;
console.log(currentIPadress);
return currentIPadress;
}
const { eq } = rubico
eq(getDNShomeIP, getCurrentIP)().then(console.log)
<script src="https://unpkg.com/rubico/index.js"></script>
documentation for eq
I am using postman to call api. I am trying to read google spread sheet row using node js. Response is printing on console but its not returning to postman.
index.js file
app.post('/myapi/getClientkey',async (req, res) => {
var response = null;
console.log("Inside myapi");
try {
response = await spreadsheet.getRecord();
} catch(err){
}
res.send(response);
});
spreadsheet.js
var config = require('./config.json');
var GoogleSpreadsheet = require('google-spreadsheet');
var creds = {
client_email: config.client_email,
private_key: config.private_key
}
var doc = new GoogleSpreadsheet(config.GOOGLE_SHEET_ID)
var sheet = null;
exports.getRecord = async function () {
console.log('Inside - getRecord');
var name = null;
var jsonObj = {};
try {
doc.useServiceAccountAuth(creds, async function (err) {
// Get all of the rows from the spreadsheet.
await doc.getRows(1, async function (err, rows) {
if(rows != null){
var oneRow = rows[0];
name = oneRow.name;
console.log("name :"+name);
jsonObj.client_name = name.toString();
}
console.log(jsonObj);
});
});
}catch(err){
console.log("err :"+err);
}
return jsonObj;
};
How to wait till response is returned from getRecord Function
Move res.send(response); inside try block and read about how to return response from an async call.
Also return jsonObj should be inside try block
I used promise call now it working.
exports.getRecord = async function () {
console.log('Inside - getRecord');
var name = null;
return new Promise( async function(resolve,reject){
try {
var jsonObj = {};
doc.useServiceAccountAuth(creds, async function (err) {
// Get all of the rows from the spreadsheet.
await doc.getRows(1, async function (err, rows) {
if(rows != null){
var oneRow = rows[0];
name = oneRow.name;
console.log("name :"+name);
jsonObj.client_name = name.toString();
}
console.log(jsonObj);
resolve(jsonObj);
});
});
}catch(err){
console.log("err :"+err);
reject();
}
}); // end of promise
};
I am trying to access return data from a do while loop, but I am unable to do so.
I have stored the information in a new variable (starships) and then returned this variable, but it says starships is not defined. I see that this may be a scoping issue, how can I resolve this?
async function getData() {
const allResults = [];
let url = 'https://swapi.co/api/starships/';
do {
const res = await fetch(url);
const data = await res.json();
url = data.next;
allResults.push(...data.results);
console.log(allResults);
} while (url !== null)
let starships = allResults;
return starships;
}
console.log(starships);
You need to get the value which is returned from getData. The most obvious way to do this with the async/await structure you have is to just await it:
async function getData() {
const allResults = [];
let url = 'https://swapi.co/api/starships/';
do {
const res = await fetch(url);
const data = await res.json();
url = data.next;
allResults.push(...data.results);
console.log(allResults);
} while (url !== null)
let starships = allResults;
return starships;
}
async function doTheDo() {
const test = await getData();
console.dir(test);
}
doTheDo();
you can do this. starships is defined inside the loop. Additionally, you are not calling getData() function. You can store that return value like this
const result = await getData();
console.log(result);
or you can directly print like this. console.log(await getData())
async function getData() {
const allResults = [];
let url = 'https://swapi.co/api/starships/';
do {
const res = await fetch(url);
const data = await res.json();
url = data.next;
allResults.push(...data.results);
console.log(allResults);
} while (url !== null)
return allResults;
}
console.log(await getData());
Async functions return a promise, which means you have to access the return value with a .then().
However, you have another problem: starships is in the scope of the function getData() which you have defined, but not called.
So first lets call your function:
async function getData() {
const allResults = [];
// do stuff
let starships = allResults;
return starships;
}
console.log(getData());
Now you will see that your log value is [object Promise] which isn't so helpful in its current form. This is because the code outside the async function is running synchronously, which means we don't have the value yet, just a promise to maybe return the value sometime in the future.
So now we need to access the promise asynchronously using the .then() like so:
async function getData() {
const allResults = [];
// do stuff
let starships = allResults;
return starships;
}
getData().then(starships => {
console.log(starships);
});
Now you should see the info you were expecting to be logged.
You can also save promise to a variable and pass it around and access it elsewhere in your code like so:
async function getData() {
const allResults = [];
// do stuff
let starships = allResults;
return starships;
}
let starshipPromise = getData();
// time & code passes...
starshipPromise.then(starship => {
console.log(starship);
}).catch(error => {
// handle error
});
And don't forget to catch your rejected promises!
See the MDN docs on Async functions: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
And if you need more info on promises, go here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise