This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
Here is my code:
const fs = require('fs');
function f() {
var arr = [];
fs.readfile(filename, function(data) {
//some code here
arr.push(someElement);
})
return arr;
}
var result = f();
console.log(result);
//I want an array of elements in it, but this produces an empty array [];
Any help would be very appreciated!
You need to use readfileSync in order to make your function synchronous, or do this:
function f() {
var arr = [];
fs.readfile(filename, function(data) {
//some code here
arr.push(someElement);
}).then(() => return arr)
}
f().then(result => console.log(result));
Adding #artur 's addition here:
readFile(), receives a function that is a callback. As specified in the doc, readFile: Asynchronously reads the entire contents of a file. So, the callback function OP gave to readFile will not be immediately called, only when the file data is ready.
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 months ago.
Can you make a function wait until a variable is set by another function? This is my example:
function setvar(){
//some process that may take a while
myvar = 'value';
}
const promise1 = new Promise((resolve, reject) => {
resolve(myvar);
});
promise1.then((value) => {
console.log(value);
});
this doesnt seem to work, the function begins even if the variable is not ready. What should I do? I dont want settimeout or setinterval because I dont know exactly how long it is going to take each time.
In the promise you'll need create a loop that would check if variable was set:
var myvar;
function setvar(){
//some process that may take a while
myvar = 'value';
}
const promise1 = new Promise((resolve, reject) => {
const loop = () => myvar !== undefined ? resolve(myvar) : setTimeout(loop)
loop();
});
promise1.then((value) => {
console.log(value);
});
setTimeout(setvar, 2000);
This question already has answers here:
Using async/await with a forEach loop
(33 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I am trying to sort names in two different array. but when I need to return the final result, it will just return the values first then do the forEach.
const available = [];
const taken = [];
const names = data.split('\n');
names.forEach(async (name, i) => {
(data.success !== undefined) ? (availabe.push(name)) : (taken.push(name));
});
return { //This returns 0 for both
available: available.length,
taken: taken.length
}
The issue is that forEach doesn't wait for async code. Check here: https://codeburst.io/javascript-async-await-with-foreach-b6ba62bbf404
Try this instead:
async function f() {
const available = [];
const taken = [];
const names = data.split('\n');
for (const name of names) {
// await request...
(data.success !== undefined) ? (availabe.push(name)) : (taken.push(name));
}
return { //This returns 0 for both
available: available.length,
taken: taken.length
}
}
Then, when you call f(), make sure you await f().
Side note: if you have very many names, this could get very slow. You're waiting for each request to complete before beginning the next one. You'll want to look into requesting all the data at once, either with a different http endpoint, or using something like Promise.all() or the async library.
The variable name "available" is misspelled as "availabe" in line 8. Other syntax errors may exist; you might try using something link jslint.com.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I'm new to JavaScript so sorry if the question is too dumb.
I have an async function getPartners() in file1.js wich returns an array like this:
return Promise.resolve(partners);
['1','2','3']
In file2.js I have an array with partnerIds and an emptyArray. My goal is when I call getPartners() in file2.js, emptyArray becomes equivalent to the function's return value. In other words I'd like to push the returned values to the emptyArray.
Currently I can get the values this way:
let emptyArray = listItems();
emptyArray.then((result) => {
console.log(result);
});
My problem is that if I try to console.log(emptyArray) outside of the .then, it's empty. I'd like to filter it too, after getting the values from the promise so I need to save the values into an array which I can call later in the code.
How can I do that?
EDIT:
This is what I want to achieve:
const { getPromiseResult } = require('./list');
let existingIds = ['1','2','3'];
let emptyArray = getPromiseResult();
emptyArray.then((resultArrayfromPromise) => {
console.log(resultArrayfromPromise) // ['2','3','4']
// filter the results by the existingIds array's elements
// get result: ['1','2','3','4']
// and get this result in a new filtered array which I can reach from the outside
});
filteredArray.dosomeotherstuff();
Since ES7, you can use async/await to get rid of then. await waits for operation to complete, and if there is a return value assigns it to the variable.
But you can only use the await in an async function so wrap your codes in it.
async function run() {
const { listItems } = require('./list');
let existingIds = ['1','2','3'];
let emptyArray = await getPromiseresult();
console.log(emptyArray); // now it's not empty
filteredArray.dosomeotherstuff();
}
run();
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
Hello I have a function that goes to the database and returns array of objects like so:
function findAlbumImages(){
remote.findAlbum.then(
res =>{
})
}
but I want to call this from another function and assign that res to array collection like so:
let newArray = findAlbumImages();
Is there a way to do this?
Sure you can, by using async/await, which is the closest you can
get to your desired syntax:
function findAlbumImages() {
return remote.findAlbum()
}
(async () => {
let newArray = await findAlbumImages()
console.log(newArray)
})()
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have 2 files
//init.js
var x = getMasterList(location);
console.log(x);
console.log("should have printed list");
And
//read.js
function getMasterList(location) {
var list = [];
ref.child(company).child("listOfLocations").once("value").then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var item = childSnapshot.val();
list.push(item);
})
});
console.log("In function");
return list;
}
The console's output is
undefined
should have printed list
In function
The problem is, because of javascript's asynchronous nature, it prints out 'x' before assigning it. I've looked at promises and it doesn't seem like it can help me since it didn't change the async behaviour. I've also looked at callbacks and I can't seem to make them work for multiple files.
Any ways of getting around this so that it only prints after 'x' has a value?
Using callbacks, you can achieve this quite easily.
read.js
function getMasterList(location, callback) {
var list = [];
//do stuff
console.log("In function");
callback(list);
}
init.js
var x = getMasterList(location, function(x){
console.log(x);
console.log("should have printed list");
});