首页 > 其他分享 >[Compose] Callback is not suitable for Async programming

[Compose] Callback is not suitable for Async programming

时间:2023-10-17 15:13:57浏览次数:29  
标签:function Compose callback text programming response Callback num stack

An example of callback implemnetation for handling async flow:

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) % 4000) + 1000;

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

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

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

// **************************************
// The old-n-busted callback way
const stack = [];
const response = {};
function getFile(file) {
  if (!(file in response)) {
    stack.push(file);
  }
  // CONS:
  // 1. It needs global variable to store extra information
  // 2. The solution is not flexable to apply elsewhere
  // 3. Won't result in a easy to test solution
  fakeAjax(file, function (text) {
    response[file] = text;
    for (let i = 0; i < stack.length; i++) {
      if (stack[i] in response) {
        if (response[stack[i]] !== false) {
          output(response[stack[i]]);
          response[stack[i]] = false;
        }
      } else {
        return;
      }
    }
    output("completed!");
  });
}

// request all files at once in "parallel"
// and print result in sequencial order
// in the end, print "completed!"
getFile("file1");
getFile("file2");
getFile("file3");

 

As we can see, the code is not easy to understand, then most like not easy to maintable and resuable.

Callback is used a lot in Node.js, but it is not good to handle async events, for multi reasons.

 

Callback hell:

If you want events happen in sequence, we have to use nested callback, which results callback hall.

 

Callback is not reasonable

For a complex async program, if we use lots of callback, it is hard to understand which callback will happen at which time. Often developers got lost in the middle.

 

Callback: iversion of contrrol

Some callback we don't have control, we might pass a callback to a third parity library, then this library will control when to call this callback

But still we need to worry about callback is called

  • Not too early
  • Not too late
  • Not too many times
  • Not too few times
  • No lost context
  • No swallowed error

But how can we handle all those trust issues? Sadly nope. 

 

There are many tries to fix the issues, but none of those are good enough:

Separate callback:

Pass two callbacks, one for error, one for success.

Problem is how can we make sure two callbacks won't be called at the same time? how to make sure callback are only trigger once? how to make sure only pass one callback without another?

So basiclly inversion of control problem, lack of trust.

function trySomething(ok, err) {
   setTimeout(() => {
       const num = Math.random()
       if (num > 0.5) {
         ok(num)
       } else {
         err(num)
       }
   }, 1000)
}

trySomething(
  (num) => {
     console.log('success:', num)
  },
  (num) => {
     console.log("Error: ", num)
  }
)

 

"Error first style":

Now we only use one callback function, and force to do error handling. But it has the same issue as "Separate callback".

How to prevent we receive both error and success callback?....

function trySomething(cb) {
   setTimeout(() => {
       const num = Math.random()
       if (num > 0.5) {
         cb(null, num)
       } else {
         cb("Too low!")
       }
   }, 1000)
}

trySomething(
  (err, num) => {
    if (err) console.log(err)
    else console.log('success:', num)
  }
)

 

标签:function,Compose,callback,text,programming,response,Callback,num,stack
From: https://www.cnblogs.com/Answer1215/p/17769735.html

相关文章

  • Programming abstractions in C阅读笔记:p179-p180
    《ProgrammingAbstractionsInC》学习第60天,p179-p180总结。一、技术总结1.palindrome(回文)(1)包含单个字符的字符串(如"a"),或者空字符串(如"")也是回文。(2)示例:“level”、"noon"。2.predicatefunction(1)predicate的意思pre-("forth")+*deik-("show"),“t......
  • 2022 China Collegiate Programming Contest (CCPC) Guilin Site(持续更新)
    Preface由于还有两周就要滚去打区域赛了,这周开始周末每天都训一场吧这场总体来说打的还可以,虽然E题这个Easy从卡局卡到3h,但由于其它的题都是一遍过所以罚时还尚可跻进Au区后面一个小时看徐神和祁神苦战K大分类讨论,虽然场下感觉摸了一个B的做法出来,但感觉实现还是太麻烦了就没写......
  • label-studio docker-compose 运行试用
    label-studio是一个支持多格式的数据标注工具,以下是基于docker-compose运行的试用环境准备docker-composeversion:"3.9"services:nginx:image:heartexlabs/label-studio:latestports:-"8080:8085"-"8081:8086"......
  • 2021 China Collegiate Programming Contest (CCPC) Guilin Site
    A.AHeroNamedMagnus#include<bits/stdc++.h>usingnamespacestd;#defineintlonglongusingpii=pair<int,int>;usingvi=vector<int>;voidsolve(){intx;cin>>x;cout<<2ll*x-1<<"......
  • Android开发 Jetpack_Compose_7 文字
    前言此篇博客主要讲解Compose里的文字相关的UI功能。文本处理相关的内容与细节较多,此篇博客尽量涵盖完整,所以博客较长需要耐心看完。  官网文档:https://developer.android.google.cn/jetpack/compose/text?hl=zh-cnText文本全部参数这里列出全部参数,下面会一个一个举......
  • Oracle 简介与 Docker Compose部署
    最近,我翻阅了在之前公司工作时的笔记,偶然发现了一些有关数据库的记录。当初,我们的项目一开始采用的是Oracle数据库,但随着项目需求的变化,我们不得不转向使用SQLServer。值得一提的是,公司之前采用的是Docker技术,所有数据库的部署都是通过DockerCompose来完成的。在今天的文......
  • Programming abstractions in C阅读笔记:p176-p178
    《ProgrammingAbstractionsInC》学习第59天,p176-p178总结。一、技术总结1.addtivesequencestn=tn-1+tn-2序列:3,7,10,17,27,44,71,115,186,301,487,788,1275,...p177,Asageneralclass,thesequencesthatfollowthispatternarecalledadditivesequen......
  • Programming abstractions in C阅读笔记:p176-p178
    《ProgrammingAbstractionsInC》学习第59天,p176-p178总结。一、技术总结1.addtivesequencestn=tn-1+tn-2序列:3,7,10,17,27,44,71,115,186,301,487,788,1275,...p177,Asageneralclass,thesequencesthatfollowthispatternarecalledadditive......
  • 2021-2022 ACM-ICPC Nordic Collegiate Programming Contest (NCPC 2021) gym 104670
    原题容易想到最短路DAG求出来,起初我以为要求最小割,但这是错误的,因为可能有多条边联通了一个点的情况,这时候选择最小割不一定是最优的我们猜想一个思路:答案一定是包含\(1\)号节点的连通块全部填\(N\),剩下的填\(S\)。发现在最短路DAG中,\(1\rightarrown\)的所有路径......
  • composer
    进入到具体的工程目录下,composerrequirexxxxxx如composerrequiretencentcloud/tencentcloud-sdk-php 包找不到的时候,可以更新镜像composer镜像更新composerconfig-grepo.packagistcomposerhttps://mirrors.aliyun.com/composer/......