I am trying to change my Protractor tests to use async/await instead of the selenium control flow, but it won't let me use await for the .getAttribute() function. All i get is this error Message: "SyntaxError: await is only valid in async function". But shouldn't .getAttribute() be async since it returns a promise?
Here is one of many examples where i get this error:
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) {
...
}
That function is not async
, and it has to be async
for await
to work. Make your callback async and it should work.
async (elem) => { //... }
If we break down your function :
// 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 ...
});
A correct syntax would be
await element.all(by.tagName('mat-list-item')).each(async (elem) => {
// ... await ...
});
But I don't know if the use of an async function is appropriate with .each
.
Myself, I like to map and return promises that I resolve using a Promise.all
, like :
async function treatElement(x) {
// ... await ...
}
await Promise.all(myArr.map(x => treatElement(x)));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.