我有以下代码,其中有两个异步执行的函数
products = [];
categories = [];
getProduct = function() {
productService.list().then(function(result) {
products = ["product1", "product2"]
});
}
getcategories = function() {
categoryService.list().then(function(result) {
categories = ["category1", "category2"]
});
}
我想要另一个接受两个参数、产品和类别的函数,类似这样:
all = function(products, categories) {
console.log(products, categories);
}
但当然,由于异步函数,我会得到未定义的结果。无论如何,在执行前面的函数后是否可以获取数据。我使用旧的JavaScript,所以我不能使用异步等待。
最佳答案
你可以使用promise链,一一调用, 请参阅:
products = [];
categories = [];
productService.list()
.then(function(result) {
products = ["product1", "product2"]; // products = result;
return categoryService.list();
}).then(function(result) {
categories = ["category1", "category2"]; // categories = result;
all(products, categories);
}).catch(function(ex) {
// Error handele
}) ;
参见示例here
还有一个选择是使用 Promise.all 它可以适合您的用例,因为您不需要一一阅读函数。在此选项中,您应该执行以下操作:
Promise.all([productService.list(), categoryService.list()]).then(function(values) {
all(value[0],value[1]);
});
关于javascript - 在旧 ES 版本中执行异步函数后获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54629294/