A
A
Alexey2019-05-26 14:05:05
JavaScript
Alexey, 2019-05-26 14:05:05

How to catch data in asynchronous code?

There are two html and js documents in the project:
I use NW.js

js
var allarrWinLoseLines = [];
var arrTheorys = nearest2(['C', 'E', 'G', 'N', 'S', 'V', 'AE', 'AG', 'AJ'])

function searchGoodTheory () {

    const XlsxPopulate = require('xlsx-populate');

    XlsxPopulate.fromFileAsync("./ArchiveRates.xlsx")
        .then(workbook => {
/*
Тут мой код, который берет данные из экселя, обрабатывает и записывает в глобальную переменную массива allarrWinLoseLines
*/
            //return workbook.toFileAsync("../tennis_pars_fast/Excel/f.xlsx");
        });
function searchGoodTheory ();

function objectWithLine (nameTheory, massWinLoss){

    function colorLine (){
        var string1 = 'rgba(';
        var string2 = ')';
        var c1 = randomInteger(1, 255);
        var c2 = randomInteger(1, 255);
        var c3 = randomInteger(1, 255);
        var c4 = randomInteger(1, 255);

        var END = [];

        return END[0] = string1 + c1 + ',' + c2 + ',' + c3 + ',' + c4 + string2;
    };


    var b = {
        label: nameTheory,
        data: massWinLoss,
        borderColor: colorLine(),
        borderWidth: 1,
    };
    return b;
};

function massObjectWithLine(endCounter) {
    var a = [];


    for (var s = 0; s < endCounter; s++){

        a[s] = objectWithLine(arrTheorys[s]+'', allarrWinLoseLines[s])//счетчик побед/проигрышей (вертикаль) к каждой теории
    };

    return a;
};


The arrTheorys[s] variable takes data quietly, because synchronous
The variable allarrWinLoseLines[s] is not defined because the code takes data without waiting for the completion of the searchGoodTheory ()
function. If we wrap the massObjectWithLine function:
setTimeout(function() {
massObjectWithLine():
}, 5000);
Then the variable allarrWinLoseLines[s] is defined, but this is only if you run the function in the document itself without html
HTML
<canvas id="myChart" width="1000" height="500"></canvas>

<script>

var temp = 5;

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: gameCounter(temp),
        datasets: massObjectWithLine(3) //количество теорий
    },
    options: {
  responsive: false,
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        },
        legend: {
            display: true,
            position: 'bottom'

        },
        tooltip: {

        }
    }

});



</script>

But when I run the html page, allarrWinLoseLines[s] is always undefined. How to fix it?
I read about async / await but did not understand how to use it for me (( tell me, please)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question