简体   繁体   English

异步 function 等待不适用于备忘录?

[英]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.我正在尝试制作异步 getData 的备忘录 function 但在缓存中添加值时,它没有等待响应并在值中添加未定义。

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);

You forgot to return data in getData.您忘记在 getData 中返回数据。 And cache[n] = await result;并且cache[n] = await result; should be cache[n] = result;应该是cache[n] = result;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM