首页 > 解决方案 > 处理对异步函数的多次调用

问题描述

我有一个导入的组件,每次用户做某事时她都会调用一个函数(比如说按下按钮),在函数中我必须以异步顺序获取一些数据,我想以异步方式运行函数调用,对该函数的调用将等到该函数完成,然后再次调用该函数。代码示例-如果我快速触发该功能 3 次:

hadlechange = async(type:string) => {
  console.log(1111111)
  let storage = await getData("G");
  console.log(22222222)

    await bla1();
    await bla2();
    console.log(333333)

  await storeData('blabla');
  console.log(4444444)
};

render() {
  return (
    <BlaBla onChange ={this.hadlechange}>)
    }

预期成绩

11111
22222
3333
4444
1111
2222
3333 
4444
1111
2222
3333 
4444

我得到了什么

1111
1111
2222
2222
1111
3333
2222
4444
3333
3333
4444
4444

我为客户端使用 JavaScript-React

标签: javascriptreactjsasynchronousasync-await

解决方案


感谢@Proximo,我想到了这个解决方案,它运行良好。也许其他人会觉得它有帮助,所以我分享我的代码:)

  constructor() {
    this.notHandling = true;
    this.saves = [];
  }

  onChange = async (status: string) => {
    this.saves.push(status);
    if (this.notHandling) {
      this.notHandling = false;
      while (saves.length > 0) {
        await blabla1(saves.pop());
         ...
      }
      this.notHandling = true;
    }
  };

  render() {
    return (
      <BlaBla onChange ={this.hadlechange}>)
      }

编辑

作为帮助功能

 export const handleMultiAsyncCalls = func => {
  let notHandling = true;
  let saves = [];
  return async function() {
    const args = arguments;
    const context = this;
    saves.push(args);
    if (notHandling) {
      notHandling = false;
      while (saves.length > 0) {
        await func.apply(context, saves.pop());
      }
      notHandling = true;
    }
  };
};

在你的课堂上,你这样称呼它-

 constructor(props) {
    super(props);
    this.handleMultiCalls = handleMultiAsyncCalls(blablaFunc);

  handleChange = (data: string) => {
    this.handleMultiCalls(data);
  };

推荐阅读