Using “await” inside non-async function

后端 未结 3 1754
梦如初夏
梦如初夏 2020-12-23 16:19

I have an async function that runs by a setInterval somewhere in my code. This function updates some cache in regular intervals.

I also have a different, synchronous

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-23 16:51

    You can call an async function from within a non-async function via an Immediately Invoked Function Expression (IIFE):

    (async () => await updateCacheForKey([key]))();
    

    And as applied to your example:

    function syncFunc(key) {
       if (!(key in cache)) {
          (async () => await updateCacheForKey([key]))();
       }
    }
    
    async function updateCacheForKey(keys) {
       // updates cache for given keys
       ...
    }
    

提交回复
热议问题