执行跳过promise语句

时间:2019-05-07 20:33:57

标签: javascript typescript promise async-await protractor

我面临一个问题,即有时会执行promise代码,有时它会跳过处理promise的语句,即使用then语句,我尝试了两种仍然存在问题的方法。

一些令人困惑的地方:

  • 我不应该像使用then那样在代码处理承诺中使用await
  • 我应该在类似的功能中使用async关键字吗

示例:

 await item.element(by.css("h4 a")).getText().then(async(text)=> {
            if (text == product) {
                await item.element(by.css("button[class*='btn-info']")).click();
            }

工作结果:

enter image description here

在上图中,变量的结果打印为80000等

我的代码如下:

第一种方法:

我替换了每个function关键字,并用fat函数放置了异步,并且还在允许的地方添加了await。另外,我先使用await然后一起使用

import { Given, When, Then } from "cucumber";
import { browser, element, by } from "protractor";
import { async } from "q";
import chai from "chai"

let assert = chai.assert;
async function selectItems(product) {
    //take 4 cards into list
    //go through each index in the list - and get the title= if title =desired title then in that index i will select add button
    await element.all(by.tagName("app-card")).each(async(item) => {

      await item.element(by.css("h4 a")).getText().then(async(text)=> {
            if (text == product) {
                await item.element(by.css("button[class*='btn-info']")).click();
            }
        })
    })
}
Given(':I will navigate to qaacamedy site', async () => {
   await browser.get("https://qaclickacademy.github.io/protocommerce/");
   await console.log("browser lunched");
  });

  When(': click on the shop and add all products in cart', async () => {
    await element(by.linkText("Shop")).click();
    await selectItems("Samsung Note 8");
    await selectItems("iphone X");

    await element(by.partialLinkText("Checkout")).getText().then(function(text) {
        let res = text.split("(");
        let x = res[1].trim().charAt(0);
        let y = x;
        console.log(y);
        assert.equal(res[1].trim().charAt(0),x);
    })
  });

  When(': I calculate all price', async () => {
    let value;
    let amount=new Array() ;
    let set= new Set();
    await element(by.partialLinkText("Checkout")).click();
    await element.all(by.css("td[class*='text-center']")).each(function(item){
          item.element(by.css("strong")).getText().then(function(text) {
               console.log(text);
               let res =text.split('.');
               value=Number(res[1].trim());
               amount.push(value);
               set.add(value);
               console.log("my value ="+value);
               console.log("my amounts"+amount);
        }) 
    })
        let add=0;
            // for (let i = 0; i < amount.length; i++) {
            //     await console.log("array value = "+amount[i]);
            //     add=add+amount[i];
            //  }
             for (let num of set) {

              await console.log("iterbale value of set = "+num);     //1 2 3 4 5 6
               add=add+num;
            }


             await console.log("total calculate value ="+add);
             await console.log("my amounts final"+amount);
  });

  Then(': some should be shown', async () =>  {
    await console.log("Then Statement");
  });

enter image description here

如以上结果所示,现在不打印报表,但有时我会得到结果

第二种方法:

我也尝试将promise函数设置为异步:

import { Given, When, Then } from "cucumber";
import { browser, element, by } from "protractor";
import { async } from "q";
import chai from "chai"

let assert = chai.assert;
async function selectItems(product) {
    //take 4 cards into list
    //go through each index in the list - and get the title= if title =desired title then in that index i will select add button
    await element.all(by.tagName("app-card")).each(async(item) => {

      await item.element(by.css("h4 a")).getText().then(async(text)=> {
            if (text == product) {
                await item.element(by.css("button[class*='btn-info']")).click();
            }
        })
    })
}
Given(':I will navigate to qaacamedy site', async () => {
   await browser.get("https://qaclickacademy.github.io/protocommerce/");
   await console.log("browser lunched");
  });

  When(': click on the shop and add all products in cart', async () => {
    await element(by.linkText("Shop")).click();
    await selectItems("Samsung Note 8");
    await selectItems("iphone X");

    await element(by.partialLinkText("Checkout")).getText().then(async(text)=> {
        let res = text.split("(");
        let x = res[1].trim().charAt(0);
        let y = x;
        await console.log(y);
        await assert.equal(res[1].trim().charAt(0),x);
    })
  });

  When(': I calculate all price', async () => {
    let value;
    let amount=new Array() ;
    let set= new Set();
    await element(by.partialLinkText("Checkout")).click();
    await element.all(by.css("td[class*='text-center']")).each(async(item)=>{
          item.element(by.css("strong")).getText().then(async(text)=> {
               await console.log(text);
               let res =text.split('.');
               value=Number(res[1].trim());
               amount.push(value);
               set.add(value);
               await console.log("my value ="+value);
               await console.log("my amounts"+amount);
        }) 
    })
        let add=0;
            // for (let i = 0; i < amount.length; i++) {
            //     await console.log("array value = "+amount[i]);
            //     add=add+amount[i];
            //  }
             for (let num of set) {

              await console.log("iterbale value of set = "+num);     //1 2 3 4 5 6
               add=add+num;
            }


             await console.log("total calculate value ="+add);
             await console.log("my amounts final"+amount);
  });

  Then(': sum should be shown', async () =>  {
    await console.log("Then Statement");
  });

在第二种方法中,我也遇到同样的问题。

还建议,处理promise函数以及以下内容是否是一种好习惯:

await element(by.partialLinkText("Checkout")).getText().then(async(text)=> {

在上述两种方法中,我都使用以下标志:

  

SELENIUM_PROMISE_MANAGER:否,

如果我使用launch.json使用调试模式,则总是会出现此问题

我的功能文件如下所示:

Feature: I am going to validate the qaacamedy site

Scenario: practice assignment

    Given :I will navigate to qaacamedy site
    When : click on the shop and add all products in cart 
    When : I calculate all price 
    Then : sum should be shown

还曾尝试删除async,async套件和量角器包,然后重新安装,一旦它可以工作,但过了一段时间,它开始向我显示问题。不了解为什么相同的代码行为会有所不同,我并没有引起问题的主要原因,因为很多天都停留在同一代码上

请调查一下,这是我在量角器上遇到的最后一个严重问题

1 个答案:

答案 0 :(得分:2)

由于您使用的是async/await,因此应避免使用传统的承诺处理方式(例如then)。看起来您正在await处理不返回承诺的方法,这实际上是没有意义的。在回调中声明async不会使调用方法异步。

selectItems的正确实现如下所示:

async function selectItems(product) {
    // async functions return a promise, use 'map' so we can wait for the promises to resolve using Promise.all
    const promises = element.all(by.tagName("app-card")).map(async (item) => {
        // use await on getText() since it returns a promise
        const text = await item.element(by.css("h4 a")).getText();
        if (text == product) {
            // return the promise produced by 'click'
            return item.element(by.css("button[class*='btn-info']")).click();
        }
    });
    return Promise.all(promises);
}

还应该更新测试,以避免将async/await语法与传统的Promise处理混合在一起。