在下面的示例中,我试图将filter
const传递到Promise.all
函数中,但是我不知道如何向下传递它,这导致它在最后一行。
如何将变量传递到Promise.all
函数中?
if (query.filter) {
const filter = '&filter=' + query.filter;
} else {
const filter = '';
}
const [companyResponse, requestsResponse] = await Promise.all([
// API Call "Read a company"
$axios.$get('/companies/' + params.company),
// API Call "List a companies requests"
$axios.$get('/companies/' + params.company + '/requests?count=5&include=owner' + filter)
]);
答案 0 :(得分:2)
const
是block scoped。因此,filter
实际上是undefined
括号之外的if
。请注意以下代码段中的错误:
const query = { filter: '' }
if (query.filter) {
const filter = '&filter=' + query.filter;
} else {
const filter = '';
}
console.log(filter)
要解决此问题,您希望在块之外定义过滤器,在这种情况下,仍可以使用三元组const
来实现:
const filter = query.filter ? `&filter=${query.filter}` : '';
const [companyResponse, requestsResponse] = await Promise.all([
// API Call "Read a company"
$axios.$get('/companies/' + params.company),
// API Call "List a companies requests"
$axios.$get('/companies/' + params.company + '/requests?count=5&include=owner' + filter)
]);
答案 1 :(得分:1)
因为您在if语句中定义了过滤器。在if语句之前执行此操作:
let filter
然后从if和else块中删除“ const”。