I am trying to understand JavaScript Async/Await feature.
So I wrote a short code to understand it but it is giving me unusual behaviour/result.
var a = 10; function load_data(data) { setTimeout(() => { a = data }, 2000); } function print() { console.log(a); } async function init() { await load_data(40); print(); } init();
I expect the value logged to be 40, but its logging 10 with async and await.
Async await depends on Promises , but you aren't making a promise anywhere in your code. As a result, awaiting load_data
doesn't wait.
Try using a promise and resolving once the timeout fires:
function load_data(data){
return new Promise(resolve => setTimeout(() => {
a=data
resolve()
}, 2000))
}
Also, we'll assume this is just for learning async/await…otherwise you should consider all the usual advice agains using global variables this way. It's a recipe for a mess once your code gets any larger
var a = 10 function load_data(data){ return new Promise(resolve => setTimeout(() => { a=data resolve() }, 2000)) } function print(){ console.log(a) } async function init(){ await load_data(40); print(); } init();
Async/Await is syntax used for handling promises, not just any asynchronous behavior. For it to work with load_data
, the function would need to return a promise object that resolves 40.
This should work how you expect:
var a = 10
function load_data(data){
return new Promise((resolve) => {
setTimeout(() => {
a=data;
resolve(a);
}, 2000)
});
}
function print(){
console.log(a)
}
async function init(){
await load_data(40);
print();
}
init();
Before learning about async await, learning about promises is essential since it's just a syntax over promises.
You should return a Promise
in load_data()
. Actually you're returning nothing, so the code is not waiting for any value to be resolved. You should do something like this:
function load_data(data){
return new Promise( resolve => {
setTimeout(() => {
a=data;
resolve(true);
}, 2000)
}
}
Your should create the promise. Furthermore, it is better not to use a global variable, but to let the promise resolve with the desired value:
function load_data(data){ return new Promise(resolve => { setTimeout(() => { resolve(data); //<-- pass data to resolve }, 2000) }); } async function init(){ let data = await load_data(40); // <--- get the promised value console.log(data); } init();
please set promise for the set your value before execute print function
var a = 10;
function load_data(data) {
return new Promise(resolve => {
a=data;
resolve('resolved');
});
}
async function init() {
var result = await load_data(40);
print();
}
function print(){
console.log(a)
}
init();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.