skip to Main Content

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


  1. 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 here

    In this case, redis does not use Promises natively, await is not needed.

    What I don’t get is your bit of code here:

    let result = await redis.get(
      redis.get('foo')
    )
    

    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:

    let result = await redis.get('foo', (result) => { console.log(result) })
    

    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

    const { promisify } = require("util");
    const getAsync = promisify(client.get).bind(redis);
    const setAsync = promisify(client.set).bind(redis);
    
    ...
    
    console.time('setFoo')
    await setAsync('foo', 'bar')
    
    ...
    
    let result = await getAsync('foo', 'bar')
    console.timeEnd('setfoo')
    
    Login or Signup to reply.
  2. 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 JavaScript Promise object. If you do not await that, the task is just added to the event loop. From your example:

    console.time('foo')
    let result = redis.get('foo')
    console.timeEnd('foo')
    

    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:

    console.time('foo')
    let result = await redis.get('foo')
    console.timeEnd('foo')
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search