javascript:异步函数问题(带循环的异步等待)
javascript中的异步函数有问题 我的函数如下所示:javascript:异步函数问题(带循环的异步等待),javascript,loops,asynchronous,promise,async-await,Javascript,Loops,Asynchronous,Promise,Async Await,javascript中的异步函数有问题 我的函数如下所示: 异步函数动画(动画){ const promises=animations.map(异步(元素,索引)=>{ const arrayBars=document.getElementsByClassName(classes.arrayElement); if(element.operation===‘更改颜色’){ 常数[barOneIndex,barTwoIndex]=元素位置; 常量barOneStyle=arrayBars[barO
异步函数动画(动画){
const promises=animations.map(异步(元素,索引)=>{
const arrayBars=document.getElementsByClassName(classes.arrayElement);
if(element.operation===‘更改颜色’){
常数[barOneIndex,barTwoIndex]=元素位置;
常量barOneStyle=arrayBars[barOneIndex]。样式;
const barTwoStyle=arrayBars[barTwoIndex]。样式;
设置超时(()=>{
barOneStyle.backgroundColor=次要颜色;
barTwoStyle.backgroundColor=次要颜色;
},指数*速度);
}
if(element.operation===‘还原颜色’){
常数[barOneIndex,barTwoIndex]=元素位置;
常量barOneStyle=arrayBars[barOneIndex]。样式;
const barTwoStyle=arrayBars[barTwoIndex]。样式;
设置超时(()=>{
barOneStyle.backgroundColor=主色;
barTwoStyle.backgroundColor=主色;
},指数*速度);
}
if(element.operation==='swap'){
设置超时(()=>{
常数[barOneIndex,新高度]=元素位置;
常量barOneStyle=arrayBars[barOneIndex]。样式;
barOneStyle.height=`${newHeight/1.4}px`;
},指数*速度);
}
});
等待承诺。所有(承诺);
console.log('finished');
}
它基本上是一个排序算法的动画,下面是该项目的链接,帮助您更容易理解:
问题是,我需要知道动画何时结束,但我尝试的一切都没有等到动画完成。我看到你的.map()函数没有返回任何承诺。你可以用它来解决这个问题
const promises = animations.map((element, index) => new Promise((resolve, reject) => {
const arrayBars = ...
...
resolve();
}))
await Promise.all(promises);
console.log('finished');
要使
promises
成为一个promises数组,则.map()
回调需要返回Promise
为此,您需要promisifysetTimeout
,标准做法是编写一个返回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');
}
注意,由于延迟在所有三种情况下都是相同的,因此源代码使用
延迟(索引*速度)更经济。然后(…)
作为外部结构,决策if(){…}if(){…}if(){…}
作为内部结构(或等效的或switch/case
结构).您没有在.map()
函数中返回任何承诺。实际上,我没有返回任何承诺,但它没有解决问题