I have a code that looks like the following
console.time('setfoo')
redis.set('foo', 'bar')
...
let result = await redis.get('foo')
console.timeEnd('setfoo')
Response time for this get
is 263ms
but when I remove await
it goes down to 0.037ms
What could be the reason?
2
Answers
Using
await
basically means "wait for this instruction to be completed before you do anything else".Not using it would make your script execute quickly, but the
result
variable will only contain an unresolved Promise. More on promises hereIn this case, redis does not use Promises natively,
await
is not needed.What I don’t get is your bit of code here:
You pass a call to redis as a parameter to another call to redis. Redis natively uses callbacks, so if you want to display the variable you got from redis, try:
Also, since redis.set() is asynchronous, by the time you try to recover your data,
'foo'
might not have been set yet.This might help you use promises with redis
EDIT: Your code re-written according to the redis documentation
Just to throw my 2 cents here: V8 (the JavaScript engine behind browsers and NodeJS) is using an event-loop (powered by
libuv
) which does not necessarily execute tasks on a separate thread. What this event loop does is essentially accepting jobs and executing them when it can. More info on the event loop here.With that being said,
.get
call adds a task to the event loop, which translates into a JavaScriptPromise
object. If you do not await that, the task is just added to the event loop. From your example:What you are actually measuring here is how much time does it take for the event loop task to be submitted?, which is insignificant.
Awaiting on the
.get
call will not only add the task to the event loop, but also block until the task executes:So, to answer your question: the two times should not be equal at all, because one example is measuring how long it takes for Redis to process the request and return the result, while the other example is measuring just how long it takes for the job to be submitted to the event loop.