仅在异步操作完成后,如何才能从数组中获取值?

时间:2018-12-20 03:22:30

标签: javascript asynchronous

我正在尝试使用Javascript创建一个简单的老虎机项目。 setInterval函数运行后的值被推入数组。一旦所有异步代码都已执行,我想在数组中获取这些值。我该怎么办?

//SLot tokens
var tokens = new Map();
tokens.set(1,'crown.jpg');
tokens.set(2,'money-bag.jpg');
tokens.set(3,'banana.png');
tokens.set(4,'cake-slice.jpg');
tokens.set(5,'pear.jpg');

var tb1 = document.querySelector('.tokenBox--1'),
    tb2 = document.querySelector('.tokenBox--2'),
    tb3 = document.querySelector('.tokenBox--3'),
    spinBtn = document.querySelector('#spinBtn');

var val1, val2, val3;


//***** I want access to this result array once all the values have been pushed into it ********
var result = [];

function rotateImg(tb, val){
    var timeRunning = 0;
    var revolveImg = setInterval(() => {
        timeRunning++;
        val = Math.floor(Math.random() * 5) + 1;
        if(timeRunning === 40){
            clearInterval(revolveImg);
            result.push(val);
            console.log(result);
        }
        tb.innerHTML = '<img src="./img/'+ tokens.get(val) +'">';
    },95);
}

function spin(){
    rotateImg(tb1, val1);
    rotateImg(tb2, val2);
    rotateImg(tb3, val3);
}

spinBtn.addEventListener('click',spin);

更新:因此,我想出了一种方法,但是所有3个插槽不再同时旋转。如果我能找出解决方案。

//SLot tokens
var tokens = new Map();
tokens.set(1,'crown.jpg');
tokens.set(2,'money-bag.jpg');
tokens.set(3,'banana.png');
tokens.set(4,'cake-slice.jpg');
tokens.set(5,'pear.jpg');

var tb1 = document.querySelector('.tokenBox--1'),
    tb2 = document.querySelector('.tokenBox--2'),
    tb3 = document.querySelector('.tokenBox--3'),
    spinBtn = document.querySelector('#spinBtn');

var val1, val2, val3;

var result = [];

function rotateImg(tb, val){
    return new Promise((resolve,reject) => {
        var timeRunning = 0;
        var revolveImg = setInterval(() => {
            timeRunning++;
            val = Math.floor(Math.random() * 5) + 1;
            if(timeRunning === 40){
                clearInterval(revolveImg);
                resolve(val);
            }
            tb.innerHTML = '<img src="./img/'+ tokens.get(val) +'">';
        },95);
    });
}

function spin(){
    rotateImg(tb1, val1).then(res =>{

        result.push(res);
        return rotateImg(tb2, val2);

    }).then(res =>{
        result.push(res);
        return rotateImg(tb3, val3);

    }).then(res => {
        result.push(res);
        console.log(result);

    }).catch(err => {

        console.log(err);

    });
}

spinBtn.addEventListener('click',spin);

0 个答案:

没有答案