Is using async in setTimeout valid? - javascript

I had a asynchronous function in Javascript and I added setTimeout to it. The code looks like that:
let timer;
clearTimeout(timer);
timer =setTimeout(() => {
(async() => {
await this._doSomething();
})();
}, 2000);
The purpose of setTimeout is to add 2 seconds before function will be run. It is to be sure that user stopped typing.
Should I remove async/await from this function now, since setTimeout is asynchronous anyway?

setTimeout adds a delay before a function call, whereas async/await is syntactic sugar ontop of promises, a way to chain code to run after a call completes, so they're different.
setTimeout has terrible error-handling characteristics, so I recommend the following in all code:
let wait = ms => new Promise(resolve => setTimeout(resolve, ms));
and then never call setTimeout directly again.
Your code now becomes:
let foo = async () => {
await wait(2000);
await this._doSomething();
}
except foo waits for doSomething to finish. This is usually desirable, but without context it's hard to know what you want. If you meant to run doSomething in parallel with other code, I recommend:
async () => { await Promise.all([foo(), this._otherCode()]); };
to join and capture errors in the same place.
If you truly meant to fire and forget _doSomething and not wait for it, you can lose the await, but you should try/catch errors:
async () => {
let spinoff = async () => { try { await foo(); } catch (e) { console.log(e); } };
spinoff(); // no await!
}
But I don't recommend that pattern, as it's subtle and can be easy to miss.

/* contrived example alert */
var foo = 'poo';
function setFoo(callback) (
setTimeout(function(){
foo = 'bar';
callback();
}, 100);
);
setFoo(function() {
alert(foo);
});

Related

Behind the scene- If I use Aync but doesn't use await in it, would it be identical with normal function? [duplicate]

This question already has answers here:
Async function without await in JavaScript
(4 answers)
Closed 2 years ago.
due to everyone's help, I got the logic behind async, promise, then, await.
I have one curisosity on top of its basic nature, which is what if
I declare async function but doesn't use await in it.
technically every argument within async function is invisibly capsulated by '.then()'
but how it works would be exactly same as synchronous function execution.
For example,
async function trackUserHandler() {
var positiondata= await getPosition();
var timerdata = await setTimer(2000)
console.log(positiondata, timerdata);
setTimer(1000).then(() => {
console.log('Timer done!');
});
console.log('one');
}
The console below doesn't run till the first two await function is done due to await(s) sitting before this.
console.log(positiondata, timerdata);
What if I don't put any await(s) in the async like below?
async function trackUserHandler() {
var positiondata= getPosition();
var timerdata = setTimer(2000)
console.log(positiondata, timerdata);
setTimer(1000).then(() => {
console.log('Timer done!');
});
console.log('one');
}
I test-run this code and behaves seemigly same as regular function without 'async'.
Of course behind the scene, everything in the function is encapsulated into 'then()' though.
Am I understanding right?
Thank you in advance.
Behind the scene- If I use Aync but doesn't use await in it, would it be identical with normal function?
Yes, you are right. An async function without an await expression will run synchronously and would be identical with normal function, but the only difference is that async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise.
For example, the following:
async function foo() {
return 1
}
...is equivalent to:
function foo() {
return Promise.resolve(1)
}
If there is an await expression inside the function body, however, the async function will always complete asynchronously.
For example:
async function foo() {
await 1
}
...is equivalent to:
function foo() {
return Promise.resolve(1).then(() => undefined)
}
Code after each await expression can be thought of as existing in a .then callback.
Yes, an async function runs synchronously till the first await, so it behaves like a regular function. It does return a Promise though:
function trackUserHandler() {
// ... code
return Promise.resolve(undefined);
}
In your example, the 2 functions won't behave the same. Without the await keyword, your variables won't capture the results returned by these 2 functions, but instead receive 2 Promises.
var positiondata = getPosition();
var timerdata = setTimer(2000);
So your console.log will print out 2 Promises instead of the values you actually expect.
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.
As you assumed, if no await is present the execution is not paused and your code will then be executed in a non-blocking manner.
const getPromise = async (s) => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(s), 500);
});
}
(async() => {
try {
const result = getPromise("a"); //no await, result has not been unwrapped
console.log('async/await -> ', result);
} catch (err) {
console.log(err);
}
})();
Async function without await in Javascript

How can I assert a function has `await`ed an async function using should.js

I have an async function f that calls another async function g. To test if f calls g, I'm stubbing g using sinon and assert it's been called using should.js.
'use strict';
require('should-sinon');
const sinon = require('sinon');
class X {
async f(n) {
await this.g(n);
// this.g(n); // I forget to insert `await`!
}
async g(n) {
// Do something asynchronously
}
}
describe('f', () => {
it('should call g', async () => {
const x = new X();
sinon.stub(x, 'g').resolves();
await x.f(10);
x.g.should.be.calledWith(10);
});
});
But this test passes even when I forget to use await when calling g in f.
One of the ways to catch this error is to make the stub return a dummy promise and check if its then is called.
it('should call g', async () => {
const x = new X();
const dummyPromise = {
then: sinon.stub().yields()
};
sinon.stub(x, 'g').returns(dummyPromise);
await x.f(10);
x.g.should.be.calledWith(10);
dummyPromise.then.should.be.called();
});
But this is a bit bothersome. Are there any convenient ways to do this?
Your example for f shows flawed code design which becomes more obvious if you write the same function without async/await syntax:
f(n) {
return g(n).then(()=>{});
}
This achieves the same behavior - whether g resolved becomes hard to tell (assuming you don't know if f returned g's promise, which is the same as not knowing whether f awaited g). If f is not interested in the result of g it should just simply return it, not hide it. Then you can simply test for the result.
If your point is that f might have to trigger several async calls sequentially awaiting several g_1, g_2,... to resolve, then you can build a test chain by asserting in the stub of g_n+1 that the dummy-promise of g_n has been resolved. In general your approach to test a dummy-promise for its status is fine.
Instead of stubbing then, you're best off stubbing g in such a way that it sets some boolean on the next event loop iteration. Then, you can check this boolean after calling f to make sure f waited for it:
it('should call g', async () => {
const x = new X();
let gFinished = false;
sinon.stub(x, 'g').callsFake(() => {
return new Promise((resolve) => {
setImmediate(() => {
gFinished = true;
resolve();
});
});
});
await x.f(10);
x.g.should.be.calledWith(10);
gFinished.should.be.true();
});
Edit: Of course, this isn't a perfect guarantee because you could have f wait on any promise that waits at least as long as it takes for g to resolve. Like so:
async f(n) {
this.g(n);
await new Promise((resolve) => {
setImmediate(() => {
resolve();
});
});
}
This would cause the test I wrote to pass, even though it's still incorrect. So really it comes down to how strict you're trying to be with your tests. Do you want it to be literally impossible to have a false positive? Or is it ok if some obvious trickery can potentially throw it off?
In most cases I find that the latter is ok, but really that's up to you and/or your team.

Testing asynchronus delay function in Karma

I have a bit of an unusual problem that I haven't found any solution for and I've been trying for quite some time. I have created a function called delay that basically creates a new Promise which resolves itself after a given amount of time. The purpose of this function is to be able to cause a delay in a chain of promises. It looks a bit like this:
const delay = ms => new Promise((resolve, reject) => {
setTimeout(resolve, ms);
});
let test = '';
const func = () => {
delay(1000).then(() => {
test = 'kek';
});
};
describe('unit tests', () => {
it('test function func', () => {
// Act
func();
// Assert
expect(test).toEqual('kek');
});
});
The problem is testing, the unit test I have provided in this example will fail because it's only after the 1000 ms delay that the variable test is set to kek.
I have tried the usual solutions like having a setTimeout inside the unit test, and also tried with jasmine.clock().tick(1001) before asserting but I can't get it to work.
Any ideas?
I actually proposed to do this (at lolex, the timers library) and am now convinced that it's a good thing that this is impossible to override the scheduler for that reason. That's because it can change the ordering of calls which can be very problematic.
Promises always resolve asynchronously, you'll have to make your test async and return the promise.
Here is how you'd write that test with an async function:
describe('unit tests', () => {
it('test function func', async () => {
// Act
let promise = func(); // wait for it to be ready
clock.tick(1001);
await promise; // wait for the promise to complete.
// Assert
expect(test).toEqual('kek');
});
});
This way you won't wait 1000 ms but the test will still work.
This works for me,
import {fakeAsync, tick } from '#angular/core/testing';
describe('When ngOnInit is invoked', () => {
it('should wait and redirect to next page', fakeAsync( () => {
component.ngOnInit(); // contains delay inside
tick(2000); // time to wait
expect(routerService.navigate).toHaveBeenCalledWith('nextStep');
}));
});

async function - await not waiting for promise

I'm trying to learn async-await. In this code -
const myFun = () => {
let state = false;
setTimeout(() => {state = true}, 2000);
return new Promise((resolve, reject) => {
setTimeout(() => {
if(state) {
resolve('State is true');
} else {
reject('State is false');
}
}, 3000);
});
}
const getResult = async () => {
return await myFun();
}
console.log(getResult());
why am I getting output as -
Promise { <pending> }
Instead of some value? Shouldn't the getResult() function wait for myFun() function resolve it's promise value?
If you're using async/await, all your calls have to use Promises or async/await. You can't just magically get an async result from a sync call.
Your final call needs to be:
getResult().then(response => console.log(response));
Or something like:
(async () => console.log(await getResult()))()
What you need to understand is that async/await does not make your code run synchronously, but let's you write it as if it is:
In short: The function with async in front of it is literally executed asynchronously, hence the keyword "async". And the "await" keyword wil make that line that uses it inside this async function wait for a promise during its execution. So although the line waits, the whole function is still run asynchronously, unless the caller of that function also 'awaits'...
More elaborately explained: When you put async in front of a function, what is actually does is make it return a promise with whatever that function returns inside it. The function runs asynchronously and when the return statement is executed the promise resolves the returning value.
Meaning, in your code:
const getResult = async () => {
return await myFun();
}
The function "getResult()" will return a Promise which will resolve once it has finished executing. So the lines inside the getResult() function are run asynchronously, unless you tell the function calling getResult() to 'await' for it as well. Inside the getResult() function you may say it must await the result, which makes the execution of getResult() wait for it to resolve the promise, but the caller of getResult() will not wait unless you also tell the caller to 'await'.
So a solution would be calling either:
getResult().then(result=>{console.log(result)})
Or when using in another function you can simply use 'await' again
async function callingFunction(){
console.log(await(getResult());
}
This is my routine dealing with await and async using a Promise with resolve and reject mechanism
// step 1 create a promise inside a function
function longwork()
{
p = new Promise(function (resolve, reject) {
result = 1111111111111 // long work here ;
if(result == "good"){
resolve(result);
}
else
{
reject("error ...etc")
}
})
return p
}
// step 2 call that function inside an async function (I call it main)and use await before it
async function main()
{
final_result = await longwork();
//..
}
//step 3 call the async function that calls the long work function
main().catch((error)=>{console.log(error);})
Hope that saves someone valuable hours
What hasn't been mentioned in this discussion are the use-case implications of the behaviour. The key thing, as I see it, is to consider what you are planning to do with the output from the top level, truly asynchronous function, and where you are planning to do that.
If you are planning to consume the output immediately, i.e. within the "async" function that is awaiting the return of the top level asynchronous function, and what you do with the output has no implication for other functions deeper in the call stack, then it does not matter that the deeper functions have moved on. But if the output is needed deeper in the call stack, then you need use "async" functions making await calls all the way down the stack to that point. Once you reach a point in the call stack where the function does not care about the asynchronous output, then you can stop using async functions.
For example, in the following code, function B uses the stuff returned from function A so is declared "async" and awaits A(). Function C() calls B(), is returned a Promise, but can move straight on before that promise is resolved because it is not interested in A()'s stuff, nor what's done with it. So C does not need to be declared as async, nor await B().
function A() {
return new Promise((resolve, reject) => {
//do something slow
resolve (astuff)
}
}
async function B() {
var bstuff = await A();
dosomethingwith(bstuff);
return;
}
function C() {
B();
dontwaitmoveon();
...
return;
}
In this next example, C() does use A()'s stuff, so needs to wait for it. C() must be declared "async" and await B(). However D() does not care about A()'s stuff, nor what's done with it, so moves on once C() returns its promise.
function A() {
return new Promise((resolve, reject) => {
//do something slow
resolve (astuff)
}
}
async function B() {
var bstuff = await A();
dosomething();
return bstuff;
}
async function C() {
var cstuff = await B();
dosomethingwith(cstuff);
...
return;
}
function D() {
C();
dontwaitmoveon();
...
return;
}
Since figuring this out, I have tried to design my code so the stuff returned by the asynchronous function is consumed as close as possible to the source.
Though your "getResult" function is async and you have rightly made an await call of myFun, look at the place where you call the getResult function, it is outside any async functions so it runs synchronously.
So since getResult called from a synchronous point of view, as soon as it is called, Javascript synchronously gets whatever result is available at the moment, which is a promise.
So returns from an async function cannot be forced to await(very important), since they are synchronously tied to the place of origin of the call.
To get what you want you can run the below,
async function getResult() {
const result = await myFun();
console.log(result);
//see no returns here
}
getResult();

Wait 5 seconds before executing next line

This function below doesn’t work like I want it to; being a JS novice I can’t figure out why.
I need it to wait 5 seconds before checking whether the newState is -1.
Currently, it doesn’t wait, it just checks straight away.
function stateChange(newState) {
setTimeout('', 5000);
if(newState == -1) {
alert('VIDEO HAS STOPPED');
}
}
Browser
Here's a solution using the new async/await syntax.
Be sure to check browser support as this is a language feature introduced with ECMAScript 6.
Utility function:
const delay = ms => new Promise(res => setTimeout(res, ms));
Usage:
const yourFunction = async () => {
await delay(5000);
console.log("Waited 5s");
await delay(5000);
console.log("Waited an additional 5s");
};
The advantage of this approach is that it makes your code look and behave like synchronous code.
Node.js
Node.js 16 provides a built-in version of setTimeout that is promise-based so we don't have to create our own utility function:
import { setTimeout } from "timers/promises";
const yourFunction = async () => {
await setTimeout(5000);
console.log("Waited 5s");
await setTimeout(5000);
console.log("Waited an additional 5s");
};
⚠️ Just for the record, you might be tempted to use a wait function to circumvent race conditions (when testing asynchronous code for example). This is rarely a good idea.
You have to put your code in the callback function you supply to setTimeout:
function stateChange(newState) {
setTimeout(function () {
if (newState == -1) {
alert('VIDEO HAS STOPPED');
}
}, 5000);
}
Any other code will execute immediately.
You really shouldn't be doing this, the correct use of timeout is the right tool for the OP's problem and any other occasion where you just want to run something after a period of time. Joseph Silber has demonstrated that well in his answer. However, if in some non-production case you really want to hang the main thread for a period of time, this will do it.
function wait(ms){
var start = new Date().getTime();
var end = start;
while(end < start + ms) {
end = new Date().getTime();
}
}
With execution in the form:
console.log('before');
wait(7000); //7 seconds in milliseconds
console.log('after');
I've arrived here because I was building a simple test case for sequencing a mix of asynchronous operations around long-running blocking operations (i.e. expensive DOM manipulation) and this is my simulated blocking operation. It suits that job fine, so I thought I post it for anyone else who arrives here with a similar use case. Even so, it's creating a Date() object in a while loop, which might very overwhelm the GC if it runs long enough. But I can't emphasize enough, this is only suitable for testing, for building any actual functionality you should refer to Joseph Silber's answer.
If you're in an async function you can simply do it in one line:
console.log(1);
await new Promise(resolve => setTimeout(resolve, 3000)); // 3 sec
console.log(2);
FYI, if target is NodeJS you can use this built-in function if you want (it's a predefined promisified setTimeout function):
import { setTimeout } from 'timers/promises';
await setTimeout(3000); // 3 sec
Use a delay function like this:
var delay = ( function() {
var timer = 0;
return function(callback, ms) {
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
Usage:
delay(function(){
// do stuff
}, 5000 ); // end delay
Credits: How to delay the .keyup() handler until the user stops typing?
You should not just try to pause 5 seconds in javascript. It doesn't work that way. You can schedule a function of code to run 5 seconds from now, but you have to put the code that you want to run later into a function and the rest of your code after that function will continue to run immediately.
For example:
function stateChange(newState) {
setTimeout(function(){
if(newState == -1){alert('VIDEO HAS STOPPED');}
}, 5000);
}
But, if you have code like this:
stateChange(-1);
console.log("Hello");
The console.log() statement will run immediately. It will not wait until after the timeout fires in the stateChange() function. You cannot just pause javascript execution for a predetermined amount of time.
Instead, any code that you want to run delays must be inside the setTimeout() callback function (or called from that function).
If you did try to "pause" by looping, then you'd essentially "hang" the Javascript interpreter for a period of time. Because Javascript runs your code in only a single thread, when you're looping nothing else can run (no other event handlers can get called). So, looping waiting for some variable to change will never work because no other code can run to change that variable.
setTimeout(function() {
$('.message').hide();
}, 5000);
This will hide the '.message' div after 5 seconds.
This solution comes from React Native's documentation for a refresh control:
function wait(timeout) {
return new Promise(resolve => {
setTimeout(resolve, timeout);
});
}
To apply this to the OP's question, you could use this function in coordination with await:
await wait(5000);
if (newState == -1) {
alert('Done');
}
Try this:
//the code will execute in 1 3 5 7 9 seconds later
function exec() {
for(var i=0;i<5;i++) {
setTimeout(function() {
console.log(new Date()); //It's you code
},(i+i+1)*1000);
}
}
Best way to create a function like this for wait in milli seconds, this function will wait for milliseconds provided in the argument:
function waitSeconds(iMilliSeconds) {
var counter= 0
, start = new Date().getTime()
, end = 0;
while (counter < iMilliSeconds) {
end = new Date().getTime();
counter = end - start;
}
}
Based on Joseph Silber's answer, I would do it like that, a bit more generic.
You would have your function (let's create one based on the question):
function videoStopped(newState){
if (newState == -1) {
alert('VIDEO HAS STOPPED');
}
}
And you could have a wait function:
function wait(milliseconds, foo, arg){
setTimeout(function () {
foo(arg); // will be executed after the specified time
}, milliseconds);
}
At the end you would have:
wait(5000, videoStopped, newState);
That's a solution, I would rather not use arguments in the wait function (to have only foo(); instead of foo(arg);) but that's for the example.
You can add delay by making small changes to your function ( async and await ).
const addNSecondsDelay = (n) => {
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, n * 1000);
});
}
const asyncFunctionCall = async () {
console.log("stpe-1");
await addNSecondsDelay(5);
console.log("step-2 after 5 seconds delay");
}
asyncFunctionCall();
If you have an asyn function you can do:
await new Promise(resolve => setTimeout(resolve, 5000));

Categories