微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 JavaScript 中的异步函数上实现 memoize 方法?

如何解决如何在 JavaScript 中的异步函数上实现 memoize 方法?

我一直在尝试用 JavaScript 编写 memoize 函数的实现。我在一个面试问题中被问到这个问题,从那以后就一直无法忘怀。我真的很感激这方面的帮助。

给定一个调用 API 的函数 -

function getSomeData(foo,callback) {
  var uri = 'http://localhost?foo=' + foo ;
  someAPIUri(uri,function onResponse(error,response,body) {
    callback(error,body);
  });
}

不使用 API,而是使用 setTimeout 来实现异步功能 -

function getSomeData(foo,callback) {
  setTimeout(()=> {
    console.log('async request');
    callback(2 * foo);
  },1000);
}

如果我们像下面这样调用两次,这意味着进行了两次异步调用,所以我们需要创建一个 memoize 函数来缓存某些输入的响应,并在任何后续调用中响应。

getSomeData(1,(response) => {
  console.log('getSomeData',response);
})

我写了这个函数-

function memoize(fn) {
  const cache = {};

  return async function() {
    const args = JSON.stringify(arguments);

    console.log('arguments passed to memoize fn: ',args);
    console.log('cache data: ',cache[args]);

    cache[args] = cache[args] || fn.apply(undefined,arguments);
    return cache[args]
  }
}

const memoizedGetSomeData = memoize(getSomeData);

const callback_fn = (response) => {
  console.log('callback response: ',response);
}

memoizedGetSomeData(1,callback_fn);

memoizedGetSomeData(1,callback_fn);

这不起作用,因为每个 memoizedGetSomeData 调用都会进行异步调用

我非常感谢您提供一些意见以使其工作并提高我的理解。

这是代码的codepen - link

控制台日志:

"arguments passed to memoize fn: " "{'0':1}"
"cache data: " undefined
"arguments passed to memoize fn: " "{'0':1}"
"cache data: " undefined
"async request"
"callback response: " 2
"async request"
"callback response: " 2

解决方法

唯一真正的问题(从我看来)是 getSomeData 是异步功能的一个糟糕的模拟,因为它不返回承诺。

function getSomeData(foo,callback) {
  return new Promise((resolve,reject) => {
      setTimeout(()=> {
          console.log('async request');
          resolve(callback(2 * foo));
      },1000);
  });
}

function memoize(fn) {
  const cache = {};
  return async function() {
    const args = JSON.stringify(arguments);

    console.log('arguments passed to memoize fn: ',args);
    console.log('cache data: ',cache);

    cache[args] = cache[args] || fn.apply(undefined,arguments);
    return cache[args]
  }
}

const memoizedGetSomeData = memoize(getSomeData);

const callback_fn = (response) => {
  console.log('callback response: ',response);
}

memoizedGetSomeData(1,callback_fn);
memoizedGetSomeData(1,callback_fn);

,

感谢@Bergi 和@dave 的评论。我了解我的代码的问题以及 memoize 函数应该如何像异步函数一样工作。

这是在异步函数上基本实现 Memoize 的最终代码 -

function getSomeData(foo,reject) => {
    setTimeout(()=> {
      console.log('async request');
      resolve(callback(2 * foo));
    },1000);
  });
}

function memoize(fn) {
  const cache = {};

  return async function() {
    const args = JSON.stringify(arguments);
    cache[args] = cache[args] || fn.apply(undefined,arguments);
    return cache[args]
  }
}

const memoizedGetSomeData = memoize(getSomeData);

const callback_fn = (response) => {
  return response;
}

// this should make async call
memoizedGetSomeData(1,callback_fn).then(response => console.log('response from async call: ',response));

// this should return response from the cache
memoizedGetSomeData(1,callback_fn).then(response => console.log('cached response: ',response));

// this should make async call (different argument)
memoizedGetSomeData(4,response));

日志:

"async request"
"response from async call: " 2
"cached response: " 2
"async request"
"response from async call: " 8

我也更新了 Codepen 代码。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。