2016-03-26 82 views
4

與此異步調用遍佈一般量角器和JavaScript的地方我有它。過去需要2行代碼現在只需10這裏有一個例子:量角器:獲取元素的ID

我寫一個量角器工具方法簡單地檢查一組相關的div和輸入文本框的某些DOM屬性。這是針對我正在開發的驗證框架。我們的想法是將量角器元素傳遞給此方法,然後基於該元素的ID檢查相關div和輸入文本框上的某些DOM屬性。這是我得到它的工作:

/** 
* Checks for error in a NUAF field 
* @param {String or Element} field . 
* @param {string} errorText expected validation error text to appear in tooltip 
*/ 
exports.checkForError = function (field, errorText) { 

    var innerCheck = function(fieldId) { 
     expect(fieldId).not.toBe(undefined); 
     var elmntd = element(by.id('divInput.'+fieldId)); 
     expect(elmntd).not.toBe(null); 
     expect(elmntd.getAttribute('tooltip')).toContain(errorText); 
     expect(exports.hasClass(element(by.id('prnt.'+fieldId)), 'has-error')).toBe(true); 
    }; 

    // this unbelievably complex block of code gets the id of the 
    // field argument. If string was passed, the fieldid is just that . 
    if (typeof field === 'string') { 
     innerCheck(field); 
    } else { 
     //what used to be field.id now needs 6 lines of code? 
     field.getAttribute('id').then(
      function(idAttribute) { 
       console.log("*********: "+idAttribute); 
       innerCheck(idAttribute); 
      } 
     ); 
    } 
}; 

的問題是:有沒有辦法寫的代碼field.getAttribute('id').then塊一個更好,更簡潔的方式。只是爲了得到元素的Id而寫所有這些只是一種恥辱。

+0

你可以使類檢查更具可讀性 - 而不是hasClass幫助器,請[自定義toHaveClass匹配器](http://stackoverflow.com/a/32699366/771848)。 – alecxe

回答

3

這不是一個異步代碼,詳細...特別是當你考慮到了可以在功能innerCheck直接傳遞給一個承諾:

// this unbelievably complex block of code gets the id of the 
// field argument. If string was passed, the fieldid is just that . 
if (typeof field === 'string') { 
    innerCheck(field); 
} else { 
    field.getAttribute('id').then(innerCheck); 
} 

應該這麼簡單