为什么我不能在 Protractor 中使用:"await .getAttribute()",即使它 returns 是一个承诺?
Why can't I use: "await .getAttribute()" in Protractor, even though it returns a promise?
我正在尝试更改 Protractor 测试以使用 async/await 而不是 selenium 控制流,但它不允许我对 .getAttribute() 函数使用 await。我得到的只是这个错误消息:"SyntaxError: await is only valid in async function"。但是 .getAttribute() 不应该是异步的,因为它 returns 一个承诺?
这是我遇到此错误的众多示例之一:
this.navBarcreator = async () => {
var mapArray = {}
await element.all(by.tagName('mat-list-item')).each((elem) => {
var tmp = await elem.getAttribute('aria-describedby')
if (tmp != null) {
...
}
})
(elem) => {
var tmp = await elem.getAttribute('aria-describedby')
if (tmp != null) {
...
}
该函数不是 async
,它必须是 async
才能使 await
起作用。让你的回调异步,它应该工作。
async (elem) => { //... }
如果我们分解你的函数:
// We have this first part which is async/await
this.navBarcreator = async () => {
// ...
});
// Then we have this part, where we are calling a function
// using each, and this function is not async/await
// but you are trying to use the keyword await in it
var mapArray = {}
await element.all(by.tagName('mat-list-item')).each((elem) => {
// ... await ...
});
正确的语法是
await element.all(by.tagName('mat-list-item')).each(async (elem) => {
// ... await ...
});
但我不知道异步函数的使用是否适合.each
。
我自己,我喜欢映射,return 承诺我会使用 Promise.all
解决,例如:
async function treatElement(x) {
// ... await ...
}
await Promise.all(myArr.map(x => treatElement(x)));
我正在尝试更改 Protractor 测试以使用 async/await 而不是 selenium 控制流,但它不允许我对 .getAttribute() 函数使用 await。我得到的只是这个错误消息:"SyntaxError: await is only valid in async function"。但是 .getAttribute() 不应该是异步的,因为它 returns 一个承诺?
这是我遇到此错误的众多示例之一:
this.navBarcreator = async () => {
var mapArray = {}
await element.all(by.tagName('mat-list-item')).each((elem) => {
var tmp = await elem.getAttribute('aria-describedby')
if (tmp != null) {
...
}
})
(elem) => {
var tmp = await elem.getAttribute('aria-describedby')
if (tmp != null) {
...
}
该函数不是 async
,它必须是 async
才能使 await
起作用。让你的回调异步,它应该工作。
async (elem) => { //... }
如果我们分解你的函数:
// We have this first part which is async/await
this.navBarcreator = async () => {
// ...
});
// Then we have this part, where we are calling a function
// using each, and this function is not async/await
// but you are trying to use the keyword await in it
var mapArray = {}
await element.all(by.tagName('mat-list-item')).each((elem) => {
// ... await ...
});
正确的语法是
await element.all(by.tagName('mat-list-item')).each(async (elem) => {
// ... await ...
});
但我不知道异步函数的使用是否适合.each
。
我自己,我喜欢映射,return 承诺我会使用 Promise.all
解决,例如:
async function treatElement(x) {
// ... await ...
}
await Promise.all(myArr.map(x => treatElement(x)));