2

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) {
            ...
        }
    })
R. Richards
  • 24,603
  • 10
  • 64
  • 64
Moke
  • 43
  • 5

2 Answers2

1
(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) => { //... }
Mirakurun
  • 4,859
  • 5
  • 16
  • 32
0

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)));
Orelsanpls
  • 22,456
  • 6
  • 42
  • 69