2016-12-20 25 views
1

我有一個函數,它正確檢索元素的索引,哪個文本===「檢查」。它清楚地印在console.log上:如何從量角器的承諾鏈中檢索數據?

function getIndex() { 
    return element.all(by.css(".palette__item.ng-scope>span")).then(function (colorList) { 
     colorList.forEach(function (elem, index) { 
      elem.getText().then(function (text) { 
       if (text == "check") { 
        console.log(index); 
        return index; 
       } 
      }); 
     }); 
    }); 
} 

然後,我嘗試了很多不同的方法,如何從中檢索數據,但沒有成功。塔最後一種方法是這樣的:

var res = null; 
webDriver.promise.fullyResolved(getIndex()).then(function (index) { 
    res = index; 
}); 
console.log(res); 

所以,在這裏我已經嘗試的功能,這guaratees任何承諾的決心裏面的init資源的價值,但它不工作,並返回null。

我認爲,我在getIndex()函數中有錯誤,也許,我已將return opertor放置在錯誤的地方,但我需要幫助。我完全不知道如何使它工作。請幫助。

回答

2

你是過於複雜的問題,使用reduce(),而不是 「的forEach」:

function getIndex() { 
    return element.all(by.css(".palette__item > span")).reduce(function (acc, elem, index) { 
     return elem.getText().then(function (text) { 
      if (text == "check") { 
       return index; 
      } 
     }); 
    }, -1); 
} 

用法:

getIndex().then(function (index) { 
    console.log(index); 
}); 

作爲一個側面說明 - 儘量不使用ng-scope類的定位器 - 它是一個純粹的技術角度特定類,它不會給你的定位器帶來意義。

+0

非常有趣,但我得到'undefined'valuse。我很抱歉,如果我的問題很蠢,我剛開始使用JS進行測試。 – SanchelliosProg

+0

@SanchelliosProg啊,nono,我很笨,忘了'return'。請再試一次。 – alecxe

+0

你是我的SUPERHERO !!!!!!!!你救了我的生命))))非常感謝你! – SanchelliosProg

1

我目前還無法對它進行調試,但這應該工作:

function getIndex() { 
    return element 
      .all(by.css(".palette__item.ng-scope>span")) 
      .then((colorList) => { 
       // get text for all elements 
       return Promise.all(colorList.map((el) = el.getText())); 
      }) 
      .then((colorList) => { 
       // we need both text and index 
       return colorList.map((el, ind) => [el, ind]) 
       // but just the elements with text "check" 
           .filter((elArr) => ellArr[0] == 'check') 
       // at this point we can throw away the text and just use the index 
           .map((elArr) => elArr[1]); 
      }) 
} 

您的基本問題是,你混功能,即回報的承諾,與其他迭代器的功能。所以當你最終致電return時,你完全失去了承諾背景。

1

一些事情: 對於初學者,您初始化承諾之外的變量,但在承諾中分配變量的值。這非常好,但請看看您向我們展示的示例中console.log()的位置。如果您將console.log語句保留在最底層,那麼在您的承諾解析之前它將最可能被執行,因此變量res的值將爲空。

您是否嘗試在承諾內註銷res的值?

回到getIndex函數...爲什麼在forEach函數中使用promise?您是否嘗試過這樣做,而不是執行以下操作:

function getIndex() { return element.all(by.css(".palette__item.ng-scope>span")).then(function (colorList) { colorList.forEach(function (elem, index) { var temp = elem.getText() if (temp == "check") { console.log(index); return index }); }); }); }

這是所有我可以和你在這個崗位所提供的信息量建議。從中獲得的關鍵教訓是更好地理解異步代碼與異步代碼的區別。