为什么我不能在Protractor中使用:“await .getAttribute()”,即使它返回一个promise?

问题描述 投票:1回答:2

我试图改变我的Protractor测试使用async / await而不是selenium控制流,但它不会让我使用等待.getAttribute()函数。我得到的只是这个错误消息:“SyntaxError:await仅在异步函数中有效”。但是.getAttribute()不应该是异步的,因为它返回一个promise吗?

以下是我收到此错误的众多示例之一:

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) {
            ...
        }
    })
javascript angular async-await protractor angular-e2e
2个回答
1
投票
(elem) => {
    var tmp = await elem.getAttribute('aria-describedby')
    if (tmp != null) {
        ...
    }

这个功能不是async,它必须是async才能使await工作。使你的回调异步,它应该工作。

async (elem) => { //... }

0
投票

如果我们打破你的功能:

// 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

我自己,我喜欢映射并返回我使用Promise.all解决的承诺,例如:

async function treatElement(x) {
   // ... await ...
}

await Promise.all(myArr.map(x => treatElement(x)));
© www.soinside.com 2019 - 2024. All rights reserved.