[Compose] Async programming: Thunks

Thunks

Sync thunk: A blocker of code which has everything ready and can return the value directly.

function add(x, y) {
  return x + y
}

const thunk = function() {
  return add(10, 15)
}

thunk() // 25

Ao thunkis pretty much the same as High order function, it can defers the result of another function call, so that you can pass thunk around to deliever the result of that function call. Notice that, the result of the function call can change over time. For example, instead of retrun add(10, 15), return Date.now(). Also thunk is similar to Promise as well.

 

Async thunk: instead of passing params to get value back, now you passing a function, and wait it to be invoke.

function addAsync(x, y, cb) {
  setTimeout(() => {
     cb(x + y)
  }, 1000)
}

const thunk = function(cb) {
  return addAsync(10, 15, cb)
}

thunk((sum) => {
    console.log(sum)
}) // 25

The power of async think is we have control over how thing is working inside thunk.

let cache = null
const thunk = function(cb) {
  if (cache) {
    return cache
  }
  cache = addAsync(10, 15, cb)
  return cache
}

For example we can add cache, the first time call the thunk might take a while to do data fetching and calcaultion, but second time it return the results right away.

Which means for consumer, you might find that calling thunk multi times, it might return the data in different time durion. Aysnc thunk normalize the time, for consumer, they don't need to worry about how the callback should be invokded. It becomes time independent.

 

Helper method to make thunk:

function makeThunk(fn) {
  var args = [].slice.call(arguments, 1)
  return function(cb) {
    args.push(cb)
    fn.apply(null, args)
  }
}

Usage:

function addAsync(x, y, cb) {
  setTimeout(() => {
     cb(x + y)
  }, 1000)
}

const thunk = makeThunk(addAsync, 10, 15)

thunk((sum) => {
    console.log(sum)
}) // 25

 


 

Coding Sync and Async thunk:

function fakeAjax(url, cb) {
  var fake_responses = {
    file1: "The first text",
    file2: "The middle text",
    file3: "The last text",
  };
  var randomDelay = (Math.round(Math.random() * 1e4) % 2000) + 1000;

  console.log("Requesting: " + url, ", in time: ", randomDelay);

  setTimeout(function () {
    cb(fake_responses[url]);
  }, randomDelay);
}

function output(text) {
  console.log(text);
}

function getFileSync(file) {
  const thunk = (cb) => {
    fakeAjax(file, cb);
  };
  return thunk;
}

function getFileAsync(file) {
  let res, fn;
  fakeAjax(file, (response) => {
    if (fn) {
      fn(response);
    } else {
      res = response;
    }
  });

  return (cb) => {
    if (res) {
      cb(res);
    } else {
      fn = cb;
    }
  };
}

// request all files at once in "parallel"
const th1 = getFileAsync("file1");
const th2 = getFileAsync("file2");
const th3 = getFileAsync("file3");

// request all files in sequence (concat version)
/**
const th1 = getFileSync("file1");
const th2 = getFileSync("file2");
const th3 = getFileSync("file3");
 */

th1((res1) => {
  output(res1);
  th2((res2) => {
    output(res2);
    th3((res3) => {
      output(res3);
      output("complete!");
    });
  });
});

 

posted @   Zhentiw  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2022-10-18 [RxJS] mergeAll - mergeMap
2022-10-18 [RxJS] Use finalize for side effects on completion
2022-10-18 [!Typescript] Tips: Access deeper parts of objects and arrays
2022-10-18 [Typescript] 56. Medium - Flip Arguments
2022-10-18 [Typescript] 55. Medium - Reverse
2022-10-18 [Jest] Note
2022-10-18 [Typescript] Tips: Ensure that all call sites must be given value
点击右上角即可分享
微信分享提示