Обещание с асинхронной функцией не ожидает выполнения - PullRequest
0 голосов
/ 14 января 2019

Я борюсь с проблемой Promise и async / await в течение последних двух дней. Я пытаюсь настроить мой protractor.conf.js, который получит имя браузера только в начале костюма и присоединится к имени костюма. Я написал специальный код репортера jasmine allure, чтобы я мог асинхронно получить имя браузера и затем использовать его с именем масти. Но ничего не работает должным образом. В коде, который я пробовал, я получаю только имя костюма. Название браузера через несколько секунд. В результате я не смог использовать это имя браузера в имени масти. Вот мой код подробно

Отредактировано

   var AllureReporter = function CustomJasmine2AllureReporter(userDefinedConfig, allureReporter) {


    let browser = {
     getCapabilities: function() {
        return new Promise(resolve => {
            setTimeout(() => {
                resolve({
                    get: str => str
                 });
            }, 2000);
        });
    }
};

    var result;
    let bName = (async () => {
        try {
            var result = (await browser.getCapabilities()).get('Browser Name');
            return result;
        } catch (err) {
            return "Error or smth"
        }
        })();

        this.suiteStarted = function(suite) {
                this.allure.startSuite(suite.fullName + result);
                console.log(suite.fullName + result);

        };

        // other methods like spec done,, spec description.

    }

индексный код от Allure, который можно изменить:

'use strict';
var assign = require('object-assign'),
            Suite = require('./beans/suite'),
            Test = require('./beans/test'),
            Step = require('./beans/step'),
            Attachment = require('./beans/attachment'),
            util = require('./util'),
            writer = require('./writer');

function Allure() {
    this.suites = [];
      this.options = {
            targetDir: 'allure-results'
            };
        }
    Allure.prototype.setOptions = function(options) {
            assign(this.options, options);
        };

        Allure.prototype.getCurrentSuite = function() {
            return this.suites[0];
        };



        Allure.prototype.startSuite = function(suiteName, timestamp) {

        this.suites.unshift(new Suite(suiteName,timestamp));
        };


    module.exports = Allure;

и класс Suit.js

    function Suite(name, timestamp) {
        this.name = name;
        this.start = timestamp || Date.now();
        this.testcases = [];
    }
    Suite.prototype.end = function(timestamp) {
        this.stop = timestamp || Date.now();
    };


    Suite.prototype.addTest = function(test) {
        this.testcases.push(test);
    };

    Suite.prototype.toXML = function() {
        var result = {
            '@': {
                'xmlns:ns2' : 'urn:model.allure.qatools.yandex.ru',
                start: this.start
            },
            name: this.name,
            title: this.name,
            'test-cases': {
                'test-case': this.testcases.map(function(testcase) {
                    return testcase.toXML();
                })
            }
        };


        if(this.stop) {
            result['@'].stop = this.stop;
        }

        return result;
    };

    module.exports = Suite;

Я получаю этот вывод после того, как отредактировал вопрос. Результат не определен в имени костюма

Executing 7 defined specs...

Test Suites & Specs:
Test for correct login undefined

1. Test for correct login 
(node:9764) [DEP0005] DeprecationWarning: Buffer() is deprecated due to 
security and usability issues. Please use the Buffer.alloc(), 
Buffer.allocUnsafe(), or Buffer.from() methods instead.
√ Navigate to the login page (5520ms)
√ Click onto language button (406ms)
√ English Language is selected (417ms)
√ Correct user name is written into email field (609ms)
√ Correct password is written into password field (486ms)
√ Login button is clicked and home page is opened with Machine on left top 

меню (5622мс) √ Кнопка выхода из системы нажата и перенаправляет на страницу входа (4049 мс)

7 спецификаций, 0 сбоев Закончено за 17.127 секунд

Я хочу получить имя браузера после строки «Test Suites & Specs:» и хочу добавить имя с именем костюма.

1 Ответ

0 голосов
/ 14 января 2019

Функция, в которой вы хотите использовать await, должна быть асинхронной. Я сделал небольшой пример для вас. надеюсь, это поможет

//The function we want to use wait in should be async!
async function myFunction() {
    //Using callback
    thisTakeSomeTime().then((res) => console.log(res)); //Will fire when time out is done. but continue to the next line

    //Using await
    let a = await thisTakeSomeTime();
    console.log(a);//will fire after waiting. a will be defined with the result.
}

function thisTakeSomeTime() {
    return new Promise((res) => {
        setTimeout(()=>{res("This is the result of the promise")}, 5000)
    })
}

myFunction();
...