首页 > 解决方案 > Javascript:在数组上映射异步函数,在每个元素上保持执行,直到它返回前一个元素

问题描述

我正在尝试构建一个抽认卡应用程序,我有两件事:一个包含每个抽认卡数据的数组和一个异步函数,该函数接收数组元素并向用户显示抽认卡。一旦执行该功能,卡片就会在屏幕上绘制。

// not actual code, do not debug

const flashcards = [card1, card2, card3] // except way more cards

function showCard(card){
    // immediately draws the card
    // waits for user interaction
    // returns a value when the user is done with the card
}

我想按顺序循环卡片,但我希望一次只显示一张卡片。问题是如果我这样做:

// not actual code, do not debug

flashcards.forEach((item) => {
    showCard(item)
})

...由于该功能是异步的,因此浏览器会同时显示所有的抽认卡,并且它们在屏幕上变得杂乱无章且无法使用。

我怎样才能循环卡片,使得每张卡片只有在用户完成与前一张卡片的交互后才被绘制(即当 showCard 返回时)?

标签: javascriptasynchronousasync-await

解决方案


我认为您不是在寻找异步解决方案,而是在寻找等待用户交互的标志。

就像是:

let currentCardIndex = 0;

while (currentCardIndex < flashcards.length) {

    showCard(flashcards[currentCardIndex]);
    currentCardIndex++;
}


推荐阅读