有一个非异步函数,我通过使用async
关键字将其作为异步函数。
以前:
exports.allowed = function (page, username) {}
之后:
exports.allowed = async function (page, username) {}
但是在使其异步之后,其功能无法正常工作。
exports.allowed = async function (page, username) {
//method body
}
exports.getMenu = function (selected, username) {
const menu = [
[
['/sss', 'sss'],
['/yyy', 'yyy'],
]
];
for (let i = 0; i < menu.length; i++) {
menu[i] = menu[i].filter((item) => this.allowed(item[0], username));
}
}
一旦我删除了async
关键字,代码就可以正常工作。我的代码有什么问题?
答案 0 :(得分:0)
异步函数返回Promise
。看到这个例子
function first() { return 2 }
typeof first() // number
async function second() { return 2 }
second() instanceof Promise // true
答案 1 :(得分:0)
将函数声明为async
时,它将返回promise
。
let three = () => 3;
let asyncThree = async () => 3;
console.log(three());
asyncThree().then(value => console.log(value));
在您的示例中,您将必须执行以下操作:
let allowed = async function(page, username) {
return page !== '/sss';
}
let getMenu = async function(selected, username) {
const menu = [
[
['/sss', 'sss'],
['/yyy', 'yyy'],
]
];
return Promise.all(menu.map(async items => {
let alloweds = await Promise.all(items.map(item => allowed(item[0], username)));
return items.filter((_, i) => alloweds[i]);
}));
}
getMenu().then(menu => console.log(menu));