简体   繁体   English

将 Promise 挂起作为变量中的值

[英]Getting Promise pending as value in the variable

I working with selenium web-driver and this is my first time working with node.js promise.我使用 selenium web-driver,这是我第一次使用 node.js promise。

I am trying the get value from getText and getAttribute and store them in an array, but getText and getAttribute keeps returning Promise我正在尝试从 getText 和 getAttribute 获取值并将它们存储在一个数组中,但 getText 和 getAttribute 不断返回 Promise

Here is my code:这是我的代码:

var a;
var nameText;
var linkText;

(async function example() {
  let driver = await new Builder().forBrowser('firefox').build();
  try {
    await driver.get('https://example.com');
    await driver.findElement(By.name('email')).sendKeys('example@example.com');
    await driver.findElement(By.name('pass')).sendKeys('pasword');
    await driver.findElement(By.id('u_0_b')).click();

   await driver.getPageSource().then( function() {

   driver.get('https://www.example.com/posts').then(function() {
    driver.findElements(By.className('title')).then(function(elements) {
      elements.forEach(function (element) {
        a = element.findElement(By.tagName('a'));

        nameText = a.getText("value").then((value) => { return value; });// Here is the issue

        linkText = a.getAttribute("href").then((value) => { return value; });// Here is the issue

        data.push({name: nameText, link: linkText});
        console.log(data);

      });
    });

    // a.then((text, href) => {
    //   console.log(text);
    //   console.log(href);
    // });
  });
});
  } finally {
    // await driver.quit();
  }
})();

If they're returning promises, then your easiest option is to make it an async function and await the results:如果他们返回承诺,那么您最简单的选择是将其设为异步函数并等待结果:

elements.forEach(async function (element) {
    a = element.findElement(By.tagName('a'));

    nameText = await a.getText("value").then((value) => { return value; });// Here is the issue

    linkText = await a.getAttribute("href").then((value) => { return value; });// Here is the issue

    data.push({name: nameText, link: linkText});
    console.log(data);

  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM