简体   繁体   English

javascript:异步函数问题(带循环的异步等待)

[英]javascript: asynchronous function problems (async await with loop)

I'm having a problem with a asynchronous function in javascript我在 javascript 中遇到异步函数问题

My function looks like this:我的函数如下所示:

async function animate(animations) {
  const promises = animations.map(async(element, index) => {
    const arrayBars = document.getElementsByClassName(classes.arrayElement);
    if (element.operation === 'change-color') {
      const [barOneIndex, barTwoIndex] = element.positions;
      const barOneStyle = arrayBars[barOneIndex].style;
      const barTwoStyle = arrayBars[barTwoIndex].style;
      setTimeout(() => {
        barOneStyle.backgroundColor = SECONDARY_COLOR;
        barTwoStyle.backgroundColor = SECONDARY_COLOR;
      }, index * speed);
    }
    if (element.operation === 'revert-color') {
      const [barOneIndex, barTwoIndex] = element.positions;
      const barOneStyle = arrayBars[barOneIndex].style;
      const barTwoStyle = arrayBars[barTwoIndex].style;
      setTimeout(() => {
        barOneStyle.backgroundColor = PRIMARY_COLOR;
        barTwoStyle.backgroundColor = PRIMARY_COLOR;
      }, index * speed);
    }
    if (element.operation === 'swap') {
      setTimeout(() => {
        const [barOneIndex, newHeight] = element.positions;
        const barOneStyle = arrayBars[barOneIndex].style;
        barOneStyle.height = `${newHeight / 1.4}px`;
      }, index * speed);
    }
  });
  await Promise.all(promises);
  console.log('finished');
}

It basically animates a sorting algorithm, here's the link of the project to help you to understand easier : https://divino.dev/Sorting-algorithms-visualizer/它基本上是一个排序算法的动画,这是项目的链接,可以帮助您更轻松地理解: https : //divino.dev/Sorting-algorithms-visualizer/

The problem is, I need to know when the animation ends, but everything I tried didn't wait the animations to finish.问题是,我需要知道动画何时结束,但我尝试的所有操作都没有等待动画完成。

I see your .map() function doesn't return any promises.我看到你的 .map() 函数没有返回任何承诺。 You can fix this with你可以用

const promises = animations.map((element, index) => new Promise((resolve, reject) => { 
   const arrayBars = ...
   ...
   resolve();
}))
await Promise.all(promises);
console.log('finished');

For promises to be an array of Promises, the .map() callback needs to return Promise.对于promises是承诺的阵列,所述.map()回调需要返回无极。

For that, you need to promisify setTimeout , for which standard practice is to write a small Promise-returning delay() function.为此,您需要承诺setTimeout ,为此标准做法是编写一个小的 Promise-returning delay()函数。

async function animate(animations) {
    function delay(ms) {
        return new Promise((resolve) => {
            setTimeout(resolve, ms);
        });
    }
    const promises = animations.map(async(element, index) => {
        const arrayBars = document.getElementsByClassName(classes.arrayElement);
        return delay(index * speed).then(() => {
            if (element.operation === 'change-color') {
                const [barOneIndex, barTwoIndex] = element.positions;
                arrayBars[barOneIndex].style.backgroundColor = SECONDARY_COLOR;
                arrayBars[barTwoIndex].style.backgroundColor = SECONDARY_COLOR;
            }
            if (element.operation === 'revert-color') {
                const [barOneIndex, barTwoIndex] = element.positions;
                arrayBars[barOneIndex].style.backgroundColor = PRIMARY_COLOR;
                arrayBars[barTwoIndex].style.backgroundColor = PRIMARY_COLOR;
            }
            if (element.operation === 'swap') {
                const [barOneIndex, newHeight] = element.positions;
                arrayBars[barOneIndex].style.height = `${newHeight / 1.4}px`;
            }
        });
    });
    await Promise.all(promises);
    console.log('finished');
}

Note that, since the delay is the same in all three cases, it's more economical of source code to have delay(index * speed).then(...) as an outer structure and the decision-making if(){...} if(){...} if(){...} as inner structures (or the equivalent or switch/case structure).请注意,由于所有三种情况下的延迟都相同,因此将delay(index * speed).then(...)作为外部结构和决策if(){...} if(){...} if(){...}作为内部结构(或等效的或switch/case结构)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM