首页 > 解决方案 > 在 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 变量将为空。是否有可能在一个函数中运行它,或者将它们分开是更好的做法吗?

标签: javascript

解决方案


我的猜测是您想先获取菜单项,然后打印收据。因此,您可能希望创建一个方法来获取要抓取的菜单项列表,然后使用回调函数作为您的打印收据。

    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 的回调


推荐阅读