Async/Await doesn't work in my example - javascript

Many JavaScript developers know about async/await and benefits of them so I try to test a old example of asynchronous action, let's see my experiment:
Undoubtedly the answer of below code is:
/*Line: 1*/ console.log(`1`);
/*Line: 2*/ console.log(`2`);
/*Line: 3*/ console.log(`3`);
//==> 123
So I wanna put a setTimeout for second line:
/*Line: 1*/ console.log(`1`);
/*Line: 2*/ setTimeout(() => {
console.log(`2`);
}, 0);
/*Line: 3*/ console.log(`3`);
//==> 132
Because of asynchronous action of second line the 2 is after the 13, so in the console 132 is showed.
I decide to use async/await feature of new JavaScript to see 123 again, so I wrote the above code like this:
(async () => {
console.log(`1`);
await setTimeout(() => {
console.log(`2`);
}, 0);
console.log(`3`);
})();
But it doesn't work and I saw 132 again in my console. Which part I did wrong or I don't know about it?

await waits for promise to be resolved. Since setTimeout is not a promise, execution of program will not wait till it is executed. You would need to wrap setTimeout() within promise as specified in first example of following link for your example to work as expected:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

setTimeout is not returning a promise. In order to get it to work, you will have to create a function returning a promise that is resolved inside the setTimeout callback.
(async () => {
console.log(`1`);
await new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
console.log(`2`);
},0);
});
console.log(`3`);
})();

You can only await a function which returns a promise. Note that await can only be used inside an async function:
async function someFunc() {
console.log(`1`);
await new Promise((resolve, reject) => setTimeout(() => {
console.log(`2`);
resolve();
}, 0));
console.log(`3`);
}
someFunc();

Await should be called on a function that returns a promise (otherwise it just returns).
setTimeout does not return a promise so you should wrap it with a function that returns a promise.
Read more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await
This code should do the work.
(async() => {
console.log(`1`);
await (() => {
return new Promise( resolve => {
setTimeout(() => {
console.log(2);
resolve()
}, 1000);
});
})();
console.log(`3`);
})();

You need to create function, for example async function foo() {}, and make await calls inside it.

Related

If I use async/await, it doesn't run in order

I have a question about the async/await execution.
example codes
async firstMethod(){
new Promise((resolve, reject)) => {
setTimeout(() => {
resolve("test1");
}, 3000);
});
}
async secondMethod() {
new Promise((resolve, reject)) => {
setTimeout(() => {
resolve("test2");
}, 1000);
});
}
await firstMethod();
await secondMethod();
So, When the two methods are executed, the following results are obtained.
test2
test1
However, if a return is attached, the result value is as follows.
async firstMethod(){
return new Promise((resolve, reject)) => {
setTimeout(() => {
resolve("test1");
}, 3000);
});
}
async secondMethod() {
return new Promise((resolve, reject)) => {
setTimeout(() => {
resolve("test2");
}, 1000);
});
}
await firstMethod();
await secondMethod();
test1
test2
Why is that? I'd appreciate it if you could explain it.
In the first case you just await the outer promises (that are the firstMethod and secondMethod functions) and the inner promises created by new Promise do not get awaited, and simply run to completion in the background.
In the second case, because of promise unwrapping you await the returned inner promises together with the outer function promises.
The reason why in the first example those 2 functions do not run in order is because you are not waiting for anything. If you try to remove the async from the function definition in the first example you will get the same result because the function does not need the async because it does not require an await. What you could do to have the same result has the second example is by adding a await before the new Promise.
Note: You also do not need the async in the second example because you are not waiting for anything, you are just returning a Promise in which you wait outside the scope.

Trying to understand async await

I'm trying to understand why this piece of code doesn't behave as I expect:
async function test() {
await setTimeout(() => {
console.log('done')
}, 1000)
console.log('it finished');
}
test();
This first prints it finished and then prints done afterwards. Shouldn't this code wait for the timeout to finish before executing console.log('it finished'); or have I misunderstood something?
You can only usefully await a promise.
setTimeout returns a timeout id (a number) that you can pass to clearTimeout to cancel it. It doesn't return a promise.
You could wrap setTimeout in a promise…
async function test() {
await new Promise( resolve => setTimeout(() => {
console.log('done');
resolve("done");
}, 1000));
console.log('it finished');
}
test();

Trying to understand between new Promise and Async/await

I have a very basic question:
This code
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
async function asyncCall() {
console.log('calling');
const result = await resolveAfter2Seconds();
console.log(result);
// expected output: "resolved"
}
asyncCall();
gives this output, which is correct:
> "calling"
> "resolved"
This one however:
async function resolveAfter2Seconds() {
setTimeout(() => {
return 'resolved';
}, 2000);
}
async function asyncCall() {
console.log('calling');
const result = await resolveAfter2Seconds();
console.log(result);
// expected output: "resolved"
}
asyncCall();
It gives instead:
> "calling"
> undefined
From javascript.info:
The word “async” before a function means one simple thing: a function
always returns a promise. Other values are wrapped in a resolved
promise automatically. So, async ensures that the function returns a
promise, and wraps non-promises in it
So there's something I am misunderstanding, isn't the resolveAfter2Seconds returning a promise in both scenarios (the resolveAfter2Seconds in the 2nd scenario has async)? If so why the output in the 2nd scenario?
Its a pretty basic beginner mistake you use return in an callback and expect to recevive something from the parent function
This here:
async function resolveAfter2Seconds() {
setTimeout(() => {
return 'resolved';
}, 2000);
}
Can be written to this here:
async function resolveAfter2Seconds() {
setTimeout(function() {
return 'resolved';
}, 2000);
}
And as you can see there is a second function and you return resolved to your callback function. There is actually no way to return this value like you want to, you will need to use Promises like in your first example
Since resolveAfter2Seconds doesnt return anything it will return by default undefined
No return = returns undefined
In the second case, you are not returning anything from the
resolveAfter2Seconds function, the return in the code is for the
callback of the setTimeout, which will not be returned by the
resolveAfter2Seconds function. Hence the undefined.
Both functions are returning a promise, the main differences between the two are when each promise resolves and what each promise resolves to. In your second function resolveAfter2Seconds, you're only returning inside of the setTimeout function, and as a result, you return back to the caller of the setTimeout callback function, not your resolveAfter2Seconds. Rather, your resolveAfter2Seconds doesn't return anything, and so it will implicitly return undefined which gets wrapped within a promise. It is more or less the same as writing:
function resolveAfter2Seconds() {
setTimeout(() => {
return 'resolved';
}, 2000);
return Promise.resolve(undefined);
}
function resolveAfter2Seconds() {
setTimeout(() => {
return 'resolved';
}, 2000);
return Promise.resolve(undefined); // returns a promise which resolves with the value of `undefined`
}
async function asyncCall() {
console.log('calling');
const result = await resolveAfter2Seconds();
console.log(result);
// expected output: "resolved"
}
asyncCall();
The above returns a Promise which resolves immediately with the value of undefined. As a result, you either need to explicitly wrap your setTimeout in a promise and resolve() (like your first resolveAfter2Seconds), or use something like a helper sleep method:
const sleep = n => new Promise(res => setTimeout(res, n));
async function resolveAfter2Seconds() {
await sleep(2000);
return "resolved";
}
async function asyncCall() {
console.log('calling');
const result = await resolveAfter2Seconds();
console.log(result);
// expected output: "resolved"
}
asyncCall();

Simple async await question with function returns

I have a simple yet perplexing issue with async functions.
I wish to simply return the value when its ready from the function.
Here is a sample code:
async function test() {
setTimeout(function() {
return 'eeeee';
}, 5000);
}
test().then(x => {
console.log(x)
});
You will get undefined been logged at once.
It's clear that you are trying to write a sleep() async function, but do remember that setTimeout is a sync function calling with a callback function will be executed at a given time, so while you are executing test(), the calling will run to end and return undefined as you have no return statement in the function body, which will be passed to your .then() function.
The right way to do this is to return a Promise that will be resolved after a given time, that will continue the then call.
async function sleep(time){
return new Promise((resolve,reject) => {
setTimeout(() => {
resolve("echo str")
},time)
})
}
sleep(5000).then((echo) => console.log(echo))
sleep function in short
const sleep = async time => new Promise(resolve=>setTimout(resolve,time))
With Promises
const setTimer = (duration) => {
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Done!');
}, duration);
});
return promise;
};
setTimer(2000).then((res) => console.log(res));
An async function has to return a promise. So to fix this, you can wrap your setTimeout function in a new promise like so:
async function test(){
return await new Promise((resolve, reject) => {
setTimeout(function(){
resolve('eeeee');
},5000);
})
}
test().then(x => {
console.log(x)
});
You can learn more about async/await on the MDN docs here. Hope this helps!

JavaScript Async/Await

I'm trying to understand JavaScript async/await. How can I rewrite the below such that the output is "Hi" then "Bye" instead of "Bye" then "Hi":
JSFiddle
sayHi()
.then(sayBye);
async function sayHi() {
await setTimeout(function() {
$("#myOutput").text('hi');
}, 1000);
}
async function sayBye() {
$("#myOutput").text('bye');
}
In order to await setTimeout it needs to be wrapped into Promise. Then with async/await you can flatten your code write it without Promise then API:
(async () => { // await has to be inside async function, anonymous in this case
await sayHi()
sayBye()
})()
async function sayHi() {
return new Promise(function (resolve) {
$("#myOutput").text('hi');
setTimeout(function() {
resolve()
}, 1000)
});
}
async function sayBye() {
$("#myOutput").text('bye');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myOutput"></div>
setTimeout doesn't return a Promise. Create a helper function to wrap it in a Promise and then you can await it.
function delay(fn, t) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(fn());
}, t);
});
}
sayHi()
.then(sayBye);
async function sayHi() {
await delay(() => {
//$("#myOutput").text('hi');
console.log("Hi");
}, 1000);
}
async function sayBye() {
//$("#myOutput").text('bye');
console.log("Bye");
}
Use the Promise way
sayHi()
.then(sayBye);
function sayHi() {
return new Promise(resolve => {
setTimeout(()=> {
$("#myOutput").text('hi'), resolve()
}, 1000);
})
}
async function sayBye() {
$("#myOutput").text('bye');
}
or the sayHi like this:
async function sayHi() {
await new Promise(resolve => {
setTimeout(()=> {
$("#myOutput").text('hi'), resolve()
}, 1000)
})
}
Using async/await is an excellent way to build acynchronous code in a quite controllable way. Promise based async function goes into microtasks depository, which event loop executes before events and methods contained in ordinary DOM refresh/web API depository (setTimeout() for example). However some versions of Opera and Firefox browsers set priority to setTimeout() over microtasks depository. Anyway, you can control order of execution if you combine Promise based function with async/await enabled function. For example:
// create function that returns Promise
let hi = () => {
return new Promise((resolve, reject) => {
setTimeout(_ => {
resolve('Hi '); // after 1500ms function is resolved and returns 'Hi '
}, 1500);
});
}
// create ordinary function that will return 'bye'
let sayBye = () => {
return 'Bye';
}
// create third function that will be async 'enabled',
// so it can use await keyword before Promise based functions
let sayHi = async () => {
let first = await hi(); // we store 'Hi ' into 'first' variable
console.log(first);
let second = sayBye(); // this execution will await until hi() is finished
console.log(second);
}
// execute async enabled function
sayHi();
We can add try / catch block inside sayHi() function for controlling error on promise reject(), but this is out of scope of your question.
Have a nice day!
You cannot use async/await for functions that are not returning Promise
When an async function is called, it returns a Promise. When the async function returns a value, the Promise will be resolved with the returned value. When the async function throws an exception or some value, the Promise will be rejected with the thrown value.
An async function can contain an await expression, that pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
Usually it is used to handle data that comes from server, because when you have multiple queries it can override previous one and you will handle the wrong one.
Async/await lets you handle exactly data you are awaiting for.

Categories