javascript - 在 Javascript 中处理异步函数
问题描述
我有 2 个 javascript 函数,它们都有自己的 ajax 请求。在伪代码中,它的工作原理如下:
fetch_menu_item {
//Make ajax call to get proper data
success: (res) => {
this.setState({items_ordered: res})
}
}
print_receipt {
this.fetch_menu_item();
//Make consts for waiter/date/time and items ordered
ordered : this.items_ordered
//Make another AJAX call to post data to the printer
}
所以这就是我不明白的。由于 Javascript 是异步的,我想我需要在 print_receipt 中调用 fetch_menu_item 函数,否则 items_ordered 变量将为空。是否有可能在一个函数中运行它,或者将它们分开是更好的做法吗?
解决方案
我的猜测是您想先获取菜单项,然后打印收据。因此,您可能希望创建一个方法来获取要抓取的菜单项列表,然后使用回调函数作为您的打印收据。
fetch_menu_items(item_list, callback){
/*forEach menu item asynchronously fetch with fetch_menu_item and
make a list of promises*/
promise.all(listofpromises).then(callback);
}
fetch_menu_item {
//Make ajax call to get proper data
success: (res) => {
this.setState({items_ordered: res})
}
}
print_receipt {
this.fetch_menu_item();
//Make consts for waiter/date/time and items ordered
ordered : this.items_ordered
//Make another AJAX call to post data to the printer
}
然后只需传递 print_receipt 作为 fetch_menu_items 的回调
推荐阅读
- django - 无法提交 django 表单
- java - 如何从包含的文件中删除/禁用/覆盖附加程序?
- powershell - 使用 mkdir 命令时的 Powershell 问题
- sql - 如何将此代码从 netezza 迁移到 db2?
- netflix-eureka - 当 Eureka 客户端检测到来自 Config Server 的配置更改时,如何避免重新注册到 Eureka 服务器?
- c - 如何从文件中逐行将单词和整数写入数组
- java - 如何在没有属性类的情况下拥有相同的程序,这里是 int 私有计数器
- css - 如果下拉下拉-“向上”,JavaFX ComboBox 边框是错误的
- oauth-2.0 - Kong OAuth2 插件客户端凭据流 provision_key 未验证
- asp.net - http 内容显示在 asp.net 应用程序中