Wait resolve promise
Wait to return value of variable from the function
HTML
See console.log
<script>
//function with resolving promise...
function x() {
var promise = new Promise(function(resolve, reject) {
window.setTimeout(function() {
//resolve('done!');
resolve(true);
//return true;
},
1000 //resolve promise after 1000 milliseconds.
);
});
return promise;
}
var waiting_value; //variable with undefined value.
//running once.
x().then(function(done) {waiting_value = done;}); //set value for this variable, after resolve promise
//using setInterval
var interval = setInterval(
function(){
if(waiting_value===true){ //if true
console.log('waiting_value = '+waiting_value+', and this returned after some time... Clear Interval...'); //show in console...
clearInterval(interval); //clear interval
}
},
100 //check each 100 milliseconds.
);
//using setTimeout
function using_variable(){ //some function
var variable_inside_function; //variable inside this function
//or here running function...
//x().then(function(done) {waiting_value = done;}); //set value for this variable, after resolve promise
//or waiting_value = async function some_async_function(){}
function waitForElement(){
if(typeof waiting_value !== "undefined"){
//CODE...
//variable exists, do what you want
console.log('variable exist');
variable_inside_function = waiting_value; //save to local variable
waiting_value = (function () { return; })(); //turn to "undefined"
console.log('waiting_value', waiting_value, 'variable_inside_function', variable_inside_function);
}
else{
console.log('variable undefined...');
setTimeout(waitForElement, 10);
}
}
waitForElement(); //run function
}
using_variable();
//OK
/*
setTimeout(
function(){
console.log(variable_inside_function); //FAILURE, because this variable_inside_function is available only inside that function...
}
,
2000 //try to display this after 2000...