javascript - 处理对异步函数的多次调用
问题描述
我有一个导入的组件,每次用户做某事时她都会调用一个函数(比如说按下按钮),在函数中我必须以异步顺序获取一些数据,我想以异步方式运行函数调用,对该函数的调用将等到该函数完成,然后再次调用该函数。代码示例-如果我快速触发该功能 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
解决方案
感谢@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);
};
推荐阅读
- azure-devops - Azure 构建管道 - 发布的 zip 文件
- python - 如何通过 Selenium 和 Python 在表格中单击 onclick 事件
- javascript - 计数器达到 0 或复位后的清除间隔
- python - 从输入字符串确定是否为 json_newline 格式
- java - 在我的活动启动开始时滞后
- javascript - 防止元素收缩
- c++ - 从内部系统调用生成调用堆栈
- mysql - 用其他字段唯一值的序号更新表中的字段
- ruby-on-rails - Rails 5 - 访问关联表中的外键以外的另一列
- c# - 如何修复 UIPickerViewModel 中的 Override 方法 GetTitle