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);
Related
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 1 year ago.
I want to assign the value inside a callback function to a variable outside of it. Here is an example with child_process.
callback.js
let variable;
require('child_process').spawn('python', ['./hello.py']).stdout.on('data', data => {
variable = data.toString();
console.log(variable);
});
console.log(variable);
hello.py
print('Hello World')
output:
undefined
Hello World
I know that the console.log at the bottom is being executed before the callback function and therefore the variable is still undefined. But how could I wait for the callback function to finish first?
Solution:
Promises seem to be the optimal answer and the code needs to be asynchronous.
async function test() {
const promise = new Promise((resolve, reject) => {
require('child_process').spawn('python', ['./test.py']).stdout.on('data', data => {
resolve(data.toString());
});
});
return promise;
}
(async function () {
let variable;
await test().then(res => {
variable = res;
});
console.log(variable);
}())
You can use a promise to wait for the callback like in this example:
let data;
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
data="abc";
resolve('foo');
}, 300);
});
myPromise.then((res)=>{console.log(data+res)})
this will print out "abcfoo"
Often the best way to wait for something asynchronous is to have asynchronous code yourself.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 2 years ago.
I am a newbie in JavaScript, trying to implement code to connect to MySQL. I am using Promise along with Async/Await function. My goal is to get the return value of the Promise object.
However, I have read and tried every possible way but still failed to understand how the Asynchronous function works in JavaScript as the return value of the function getData() still return an object
Promise { < pending > }
I also tried to use then but it still returns the same result. I would really appreciate it if someone can show me what I have misunderstood or where I did wrong in this function. Thank you!
Here is my JS code:
function test_connection() {
var connection = #MySQLConnectionObject;
return new Promise((resolve, reject) => {
connection.connect((error, result) => {
if (error) {
reject(error)
} else {
connection.end();
resolve("Successfully Connected!");
}
});
});
}
async function getData() {
var result = await test_connection()
return result;
}
var result = getData();
console.log(result);
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.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
The below code is not returning a value back but it console logs out fine. Any ideas how I can set the value of X?
var dbSize = dbo.collection('Items').count()
var x = 0
x = dbSize.then(len => {
return len
})
This is what is being logged 'Promise { }' however if I simply write this:
dbo.collection('Items').count()
var x = 0
dbSize.then(len => {
console.log(len)
})
then It logs out fine.
you can warp your code with an async function and then use await to make your code work like synchronized code
const a = async () =>{
var dbSize = await dbo.collection('Items').count()
console.log(dbSize)
}
a();
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
The community is reviewing whether to reopen this question as of 9 days ago.
I just want to get the return value from setTimeout but what I get is a whole text format of the function?
function x () {
setTimeout(y = function () {
return 'done';
}, 1000);
return y;
}
console.log(x());
You need to use Promises for this. They are available in ES6 but can be polyfilled quite easily:
function x() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('done!');
});
});
}
x().then((done) => {
console.log(done); // --> 'done!'
});
With async/await in ES2017 it becomes nicer if inside an async function:
async function() {
const result = await x();
console.log(result); // --> 'done!';
}
You can't get a return value from the function you pass to setTimeout.
The function that called setTimeout (x in your example) will finish executing and return before the function you pass to setTimeout is even called.
Whatever you want to do with the value you get, you need to do it from the function you pass to setTimeout.
In your example, that would be written as:
function x () {
setTimeout(function () {
console.log("done");
}, 1000);
}
x();
Better to take a callback for function x and whatever task you want to perform after that timeout send in that callback.
function x (callback) {
setTimeout(function () {
callback("done");
}, 1000);
}
x(console.log.bind(console)); //this is special case of console.log
x(alert)
You can use a combination of Promise and setTimeOut like the example below
let f1 = function(){
return new Promise(async function(res,err){
let x=0;
let p = new Promise(function(res,err){
setTimeout(function(){
x= 1;
res(x);
},2000)
})
p.then(function(x){
console.log(x);
res(x);
})
});
}
I think you want have flag to know event occured or no. setTimeout not return a value. you can use a variable to detect event occured or no
var y="notdone";
setTimeout(function () {
y="done";
}, 1000);
You can access variable y after timeout occured to know done or not