Return value in function from a promise block

后端 未结 3 1867
小蘑菇
小蘑菇 2020-11-29 13:55

I\'m trying to write a function (using WebdriverJS lib) that iterates through a list of elements, checks the names and build an xpath locator that corresponds to that name.

3条回答
  •  余生分开走
    2020-11-29 14:17

    Here you go, I cleaned it up a bit. This will actually return an error if one is experienced in the nested promises:

    var findCreatedTask = function() {
      var Promise = require('bluebird');
      var createdTask;
      return driver.findElements(By.xpath("//div[@id='Tasks_Tab']"))
        .then(function(tasks) {
          return Promise.map(tasks, function(task){
            return driver.findElement(By.xpath("//div[@id='Tasks_Tab'][" + index + "]//div[@class='task-title']")).getText()
          }).then(function(taskTitles){
            for (let i = 0; i < taskTitles.length; i++){
              if(taskTitles[i] === 'testName'){
                createdTask = "//div[@id='Tasks_Tab'][" + i + "]";
                return createdTask;
              }
            }
          });
      });
    };
    

    You call it using

    findCreatedTask.then(function(res){
       //do your thing
    }).catch(function(err){
       console.error(err.stack);
    });
    

提交回复
热议问题