javascriptasync-awaitmemo

Async function await is not working with memo?


I'm trying to make a memo function of async getData but at the time of adding the value in the cache, it's not waiting so the response and adding undefined in the value.

async function getData(searchKey){
    try{
    const response= await fetch(`http://openlibrary.org/search.json?title=${searchKey}`)
    const data = await response.json();
    showSuggestions(data , searchKey);
    }catch(err){
        console.log(err);
    }
}

const memoize = (fn) => {
    let cache = {};
    return async (...args) => {
      let n = args[0];  // just taking one argument here
      if (n in cache) {
        console.log('Fetching from cache', cache);
        return cache[n];
      }
      else {
        console.log('Calculating result');
        let result = await fn(n);
        cache[n] =  await result;
        return result;
      }
    }
  }
  // creating a memoized function for the 'add' pure function
  const memoizedgetData = memoize(getData);

Solution

  • You forgot to return data in getData. And cache[n] = await result; should be cache[n] = result;