@ArtGMlg

Как правильно изменять переменные в асинхронной функции?

У меня есть некая асинхронная функция, которая проверяет, допустима ли точка и, если нет, смещает ее на канвасе. При этом новую точку нужно снова проверить:
let proc = get_proc();

let s = [0, 0];
let q = [s];

const algorithm = (processor, queue) => new Promise((resolve, reject) => {
    let qu = queue;
    let point = queue.shift();
    processor.check(point[0], point[1]).then(x => {
        if (!x.allowed) {
            processor.move_left(point[0], point[1]).then(() => qu.push(([point[0]-1, point[1]]));
            return false;
        } else {
            return true;
        }
    }).then(st => {
        if (st) {
            s = point;
            resolve(point);
        } else {
            resolve(algorithm(processor, qu));
        }
    })
})

algorithm(proc, q).then(() => console.log(s))


Но проблема заключается в том, что в переменную qu новая точка не добавляется, из-за чего на следующем вызове algorithm переменная queue становится undefined.
  • Вопрос задан
  • 57 просмотров
Пригласить эксперта
Ответы на вопрос 1
i229194964
@i229194964
Веб разработчик
let proc = get_proc();

let s = [0, 0];
let q = [s];

const algorithm = (processor, queue) => new Promise((resolve, reject) => {
    let qu = queue;
    let point = queue.shift();
    processor.check(point[0], point[1]).then(x => {
        if (!x.allowed) {
            processor.move_left(point[0], point[1]).then(() => {
                qu.push([point[0] - 1, point[1]]);
                resolve(qu);
            });
        } else {
            resolve(true);
        }
    }).then(st => {
        if (st) {
            s = point;
            resolve(point);
        } else {
            return algorithm(processor, qu);
        }
    }).catch(err => reject(err));
});

algorithm(proc, q).then((result) => {
    if (result !== null) {
        q = result;
        return algorithm(proc, q);
    }
}).then(() => console.log(s));
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы