This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I have a txt file containing a list of all Italian words (link) that I want to read and then convert to an array of words, but I'm a bit stuck on the reading part. The file was originally downloaded from the web, so it might or might not have some encoding issues.
To read the file, I am using Fetch, with the same code suggested in the top answer of this post. After reading it, if I use alert(storedText) the text is correctly displayed; however, if I try var s = storedText.toString() and then alert(s) I get "undefined" in the alert box.
I guess there is some problem when reading the file, but I'm rather new to JavaScript and I can't figure out what exactly the problem is. Do you guys have any idea?
Edit: this is my full code
var storedText;
fetch('http://doodlemarty.unaux.com/wp-content/uploads/2021/08/parole.txt')
.then(function(response) {
response.setContentType("text/html;charset=UTF-8");
response.text().then(function(text) {
storedText = text;
done();
});
});
var s = storedText.toString();
var fullList = storedText.split('\n');
function test () {
//first try:
alert(storedText);
//second try:
alert(s);
//trying split:
alert(fullList[2]);
};
I have the test function execute when a button is clicked.
This seems like a async issue with promises. You are trying to access storedText before its value is updated in the fetch operation.
Try this:
var storedText;
var s;
var fullList;
async function callFetch() {
let response = await fetch('http://doodlemarty.unaux.com/wp-content/uploads/2021/08/parole.txt')
response.setContentType("text/html;charset=UTF-8");
let text = await response.text();
storedText = text;
}
function setVariables() {
s = storedText.toString();
fullList = storedText.split('\n');
}
async function test() {
await callFetch();
setVariables();
//first try:
alert(storedText);
//second try:
alert(s);
//trying split:
alert(fullList[2]);
};
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I hope this is not a duplicate. So far I could find a few tutorials and questions about this - but usually everyone just wants to log the results of their code to console, which is not helping me.
I want to fetch some data from an API to plot it on a website.
The fetching seems to work fine, because I can log the results inside the fetch.then() to the console. But (obviously) they do not make their way outside of the fetch.
The only solution I was able to find is to wrap this whole thing in another function or to write a function that works with the data fetched inside of the .then().
I couldn't make the first idea work, because I cannot return anything for the same reason as above (the data does not make it's way outside of the .then()).
The second one is problematic, because I simply want to plot the results from a few .json entries to a Plotly plot. And I have honestly no idea how to place this inside of a function.
// Arrays for results
var sugars = [];
var times = [];
// fetch the BG data from the API and write results into arrays
fetch(url)
.then((resp) => {return resp.json()})
.then( (result) => {
// read glucose values from json
// logging the results/sugars/times to console from here works!
for (let i = 0; i < n_entries; i++) {sugars[i] = result[i]["sgv"]}
for (let i = 0; i < n_entries; i++) {times[i] = -i * timestep}
});
var x1;
var y1;
/*
// Dummy data to test plotly, these WORK for some reason.
x1 = [0, -5, -10, -15, -20];
y1 = [123, 119, 113, 107, 102];
*/
// These values, however, don't work:
/*
x1 = times;
y1 = sugars;
// this yields 'undefined' errors:
console.log(times)
*/
Maybe you can try to separate your fetch and return the data to a function where you use the data to do what you want. You can try something like this - I think it is the same as what other people commented.
//make the fetch and return response data as json
async function getData() {
let url = 'your url';
try {
let resp = await fetch(url);
return await resp.json();
} catch (error) {
console.log(error);
}
}
//do whatever you want with the data response
async function myFunc() {
let data = await getData();
//do some stuff with your data here
}
//call the function
myFunc();
Take at look at this link if you get stuck.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
Long story short. I'm trying to learn javascript. And i've been googling for about 4 hours straight right now. And i cant find the answer to my current problem, so i'm assuming i'm looking at this the wrong way.
I'm trying to create a slackbot. The bot is connected, and can look for messages so that part is working.
I've (tried to)create(ed) a function that gets the userID of everynew message based on the name i set in. In my mind this function returns the userID, and that i can later down the code check if userID is in message.text, if it is do something.
I'm assuming it has something to do with that .then function. Can i even return data from that .then function? or can u just use that data inside of that function.
I have several return functions as i was trying to just return it from wherever u could.
function getuserid(botname){
var id = ''
var getbotid = bot.getUsers();
getbotid.then(function(value){
for(var i=0;i<value.members.length;i++){
if(value.members[i].name == botname){
id = value.members[i].id
console.log(id);//this logs what i want.
return id
}
} return id
})
return id
}
var botid = getuserid('jokester');
console.log(botid);
I'm not sure but in my experience, if you return getbotid() then actually you return a promise and you can use it .
function getuserid(botname){
var id = ''
//************Here I return getbotid
return bot.getUsers().then(function(value){
for(var i=0;i<value.members.length;i++){
if(value.members[i].name == botname){
id = value.members[i].id
console.log(id);//this logs what i want.
return id
}
} return id
})
return id
}
//Now you can use it
getuserid('jokester').then(id => console.log(botid));
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
In an external .js file, I have defined and initialized the variable degree, and I have a function that pulls in the most current SQS call from AWS. When I run the script, it all works and degree prints fine to the console. When I did console.log(typeof degree) it was defined as a string, which is fine for my purposes. The only issue is that when loading the HTML web page, the variable prints as 'undefined'. This is my simplified JavaScript within the HTML file:
<li id="temp"></li>
<script src="server.js"></script>
<script>
var myVar = setInterval(myTimer, 1000);
function myTimer() {
document.getElementById("temp").innerHTML = degree;
}
</script>
I have tried moving the inner JavaScript above the list item, I have moved the document.getElement line outside of the timer (all of my other code in the timer works and shows up fine). Thanks for any insight to this problem! This is the simplified JavaScript:
var degree = 0;
sqs.receiveMessage(params, function(err, data) {
var jObject = JSON.stringify(data.Messages[0]);
var parts = jObject.split(":");
temp = String(parts[4]);
degree = temp.substring(1,5);
});
I think you try console.log(degree) with in the function itself to show if it is work or not this is first , outside the function the degree is undefined because the function itself return nothing try this code
var degree = 0;
sqs.receiveMessage(params, function(err, data) {
var jObject = JSON.stringify(data.Messages[0]);
var parts = jObject.split(":");
temp = String(parts[4]);
degree = temp.substring(1, 5);
return degree;
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have a question regarding setting 'public' variable in JavaScript. Here is my code:
var storeKey;
firebase.database().ref('stores').orderByChild('storeAddress').equalTo('Blk 167').once('value', function(snapshot) {
var storeData = snapshot.val();
if (storeData){
console.log('exists');
}else{
storeKey = firebase.database().ref('stores').push({
storeName : "store1",
storeAddress : "Blk 167"
}).getKey();
//console.log("STORE " + storeKey);
}
});
console.log("STORE " + storeKey);
I am checking if the address exists before adding new record into Firebase. However, if I put the console.log at the last line, I get undefined. It only returns a value if I print it out inside the else statement.
I wanted to separate the storeKey out before I need that data in other places and I don't want my code to be nested inside the else statement. Any idea how to achieve this?
Your function accepts a callback, the console.log is called before the callback, that's why its undefined One way to "solve" it is using promises. e.g.
const deferred = q.defer();
firebase.database().ref('stores').orderByChild('storeAddress').equalTo('Blk 167').once('value', function(snapshot) {
var storeData = snapshot.val();
if (storeData){
console.log('exists');
}else{
storeKey = firebase.database().ref('stores').push({
storeName : "store1",
storeAddress : "Blk 167"
}).getKey();
deferred.resolve(storeKey);
}
});
deferred.then(console.log)
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
can you please tell me what i am doing wrong here. i know its simple problem but took whole day for this.
all i was trying to do was adding a value to array called messages from json file.
function get_message(params) {
var messages = ["hello", "bb"]; // i have manually assigned the value here for testing purpose
$.getJSON("messages.json", function( json ) {
var test="JSON Data: " + json.login.loginsuccess.excited.en[0] ; // this is working fine. just retrieving 1 value for testing
console.log(test); // it shows the output get from json file. this line is also fine
messages.push(test);// here is the problem. why i am not being able to add value to this array messages?
});
alert(messages[2]);// it gives me out put undefined
var index = Math.floor(Math.random() * messages.length);
return messages[index];
}
thanks
It's because the AJAX call is asynchronous, so the alert() line is firing before the data is pushed to the messages array. Try moving your code to show the alert inside the callback function.
getJson is asynchronous, so you need to ensure that you're not checking the messages array too soon. You should probably use a callback to get the information you need.
function get_message(params, callback) {
var messages = ["hello", "bb"];
$.getJSON("messages.json", function( json ) {
var test="JSON Data: " + json.login.loginsuccess.excited.en[0];
console.log(test);
messages.push(test);
alert(messages[2]);
var index = Math.floor(Math.random() * messages.length);
callback(messages[index]);
});
}
And use like:
get_message(params, function (data) {
console.log(data);
});