Asynchronous Method In JavaScript [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
Below is my JS Method
function test(key, language) {
var uri = '/Resources/ValidationMessages.json';
fetch(uri).then(response => {
return response.json();
}).then(data => {
console.log('Inside Function - ' + data[key]);
return data[key];
}).catch(err => {
console.log(' Error ');
});
}
And after calling this method as
var v = test('spnrequiredRegisterEmail');
console.log('Outside Function - ' + v);
Inside the function it print value but Outside Function statement is always undefined.
The solution that I am trying to achieve is that I have to set some text in n number of span as inner text, which will come through this function call after passing the respective key, but every span displays undefined as inner text
It won't wait for a method to finish , so how can I solve this issue?

Try using async / await
async function test(key, language) {
try {
var uri = '/Resources/ValidationMessages.json';
var resp = await fetch(uri);
var data = resp.json();
console.log('Inside Function - ' + data[key]);
return data[key];
catch(err) {
console.log(err);
}
}

Related

How can I assign value in "then" in Node JS in a global variable to use later [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 4 months ago.
This post was edited and submitted for review 4 months ago and failed to reopen the post:
Original close reason(s) were not resolved
let city;
let c;
async function getCity() {
let apiKey = '9ddf7197ff9633535259c99aa0716c329981d1514f05e2e1e2015803';
let response = await fetch(`https://api.ipdata.co?api-key=${apiKey}`);
let data = await response.json();
city = data.city;
return city;
}
getCity().then(
function (value) {
c = value.city;
},
function (error) {
console.log(error)
}
);
console.log(c);
How do I assign a value to a global variable so that it can be use anywhere in the code. As I tried this method but I am getting "undefined" as my solution from console.log.
I don't think you need to await when calling the function getCity(). I wasn't able to get a value, but I fixed the error. Try this:
let city;
async function getCity() {
let apiKey = 'api_key';
let response = await fetch(`https://api.ipdata.co?api-key=${apiKey}`);
let data = await response.json();
city = data.city;
return city;
}
getCity().then(
function (value) {
console.log(value)
},
function (error) {
console.log(error)
}
);

Simple javascript function returns undefined [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
function emailExist(e) {
const sqlstmt = "SELECT email FROM somewhere WHERE email = ? LIMIT 1";
db.query(sqlstmt, [e], (err, result) => {
//supposed to return 0 or 1
return result.length
});
}
console.log(emailExist('someone#gmail.com')); //returns undefined
I tried using variables, still returned undefined
The problem is that you are trying to return a value from the callback.
To get the value from the callback, which will be called after a certain period of time. There are several ways to solve this problem, for example, you can wrap your callback in a Promise:
function query(sqlstmt) {
return new Promise((resolve, reject) => {
db.query(sqlstmt, [e], (err, result) => {
if(err) {
return reject(err);
}
resolve(result.length);
});
})
}
async function emailExist(e) {
const sqlstmt = "SELECT email FROM somewhere WHERE email = ? LIMIT 1";
const result = await query(sqlstmt);
return result;
}

Console.log not waiting for the promise [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I am very new to JavaScript, trying to understand the concepts of asynchronous function. So, basically I wrote a webScraper for RateMyProfessor using nightmare. This is the function:
var Nightmare = require("nightmare"),
nightmare = Nightmare();
const baseURL =
"https://www.ratemyprofessors.com/search.jsp?queryBy=schoolId&schoolName=University+of+California+Santa+Barbara&schoolID=1077&queryoption=TEACHER";
const getRatingProfessor = (professorName) => {
let rating;
let nameSplitter = professorName.split(" ");
if (nameSplitter.length > 2) {
professorName = nameSplitter[0] + " " + nameSplitter[1];
}
nightmare
.goto(baseURL)
.click("#ccpa-footer > .close-this")
.type("#professor-name", professorName)
.wait(1000)
.evaluate(() => {
var resultList = document.querySelectorAll("a .rating");
//if no result is found
if (typeof resultList === "undefined" || resultList.length == 0) {
return "Not Found";
}
//Found the professor with exact name
if (resultList.length == 1) {
return document.querySelector("a > .rating").innerHTML;
}
//conficting similar professor names (rare case)
if (resultList.length >= 2) {
return "Cannot Determine";
}
})
.end()
.catch((err) => {
console.log(err);
})
.then((text) => {
rating = text;
console.log(professorName, text);
});
return rating;
};
console.log(getRatingProfessor("XXXXX"));
If I run this program, it gives the following output:
undefined
SomeProfName 4.8
It seems like the function returned the rating to console.log without waiting for the promise. Why isn't function not waiting for the nightmare promise to get resolved. More importantly, why isn't the value of rating getting updated; or it has been updated but console.log doesn't want to wait for the function?
Sorry, these questions may look absurd, but I would really appreciated the answers :0
Your function explicitly does not return anything hence will return undefined by default. What you are getting is correct but within the then()...
If you wanted to return an async result you'd need to declare your function as async and then await the result.
const getRatingProfessor = async (professorName) => {
let rating;
let nameSplitter = professorName.split(" ");
if (nameSplitter.length > 2) {
professorName = nameSplitter[0] + " " + nameSplitter[1];
}
await text = nightmare...
return text;
};
(async () => {
console.log(await getRatingProfessor("XXXXX"));
}
)()

How to return a value from inside of an event that is located inside the main function? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I'm creating a function in Google Cloud functions that should return a base64 pdf. I'm using the pdfmake library. With a console.log() I can see that the base64 is generated correctly, but I'm unable to return the value to the caller.
The pdf doc is closed with .end(), and that triggers the event .on('end'). The problem is that I can't seem to return the value from inside the event.
When I put the return inside the event (as it is right now), firebase waits out and return a null.
If I put the return after the .end(), the value returned is null, as if the event was async and did't have any time to proccess.
exports.pdf = functions.https.onCall((data, context) => {
var PdfPrinter = require('pdfmake');
var printer = new PdfPrinter(fonts);
let fonts = {...};
var docDefinition = {...};
var pdfDoc = printer.createPdfKitDocument(docDefinition);
let chunks = [];
let pdfBase64 = null;
pdfDoc.on('data', (chunk) => {
chunks.push(chunk);
});
pdfDoc.on('end', () => {
const result = Buffer.concat(chunks);
pdfBase64 = 'data:application/pdf;base64,' + result.toString('base64');
console.log(pdfBase64);
return {pdfBase64: pdfBase64};
});
pdfDoc.end();
});
How could I return the value?
You need to return a promise that eventually resolves with the data to send to the client. Try something like this:
// everything above stays the same
const p = new Promise((resolve, reject) => {
pdfDoc.on('end', () => {
const result = Buffer.concat(chunks);
pdfBase64 = 'data:application/pdf;base64,' + result.toString('base64');
console.log(pdfBase64);
resolve({pdfBase64: pdfBase64});
});
})
pdfDoc.end();
return p;

making a .then() function return a promise to be used by another 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 am using this native script firebase plugin, which makes me use this function:
getValue() {
var value;
firebase.getValue('/companies')
.then(result => {
console.log(JSON.stringify(result));
value = result;
return result;
})
.catch(error => {
console.log("Error: " + error);
return error;
});
return value;
}
If I import it in another file and use it like this:
var myValue = this.myFirebaseService.getValue();
If I run it the first time it returns undefined but the second time it returns the value.
My question is how do I make the firebase function return a promise so I can make my second statement wait for it.
The firebase function you're referring to is returning a promise. That's why you can use .then and .catch after calling the getValue function.
If you return the firebase promise from getValue(), like this:
getValue(){
return firebase.getValue('/companies');
}
You'll be able to call getValue() whenever you like, but you'll have to execute the code after getValue() (which is a promise) is resolved. Like so:
getValue().then(function(value) {
console.log(value);
});
I would read up on promises if you don't understand this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
You can initialize myValue after the result has been received from the then block.
Something like this:
var myValue;
function getValue() {
return firebase.getValue('/companies');
}
myValue = getValue().then(result => {
const value = JSON.stringify(result);
console.log(value);
return value;
})
.catch(error => {
console.log("Error: " + error);
});
}

Categories