javascript - 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 返回时)?
解决方案
我认为您不是在寻找异步解决方案,而是在寻找等待用户交互的标志。
就像是:
let currentCardIndex = 0;
while (currentCardIndex < flashcards.length) {
showCard(flashcards[currentCardIndex]);
currentCardIndex++;
}
推荐阅读
- .net - 如何在 web api 中处理重复的帖子请求
- java - 移动设备上符合 JAX-RS 的实现
- javascript - 在 WebPack 中跳过带有 js 文件的条目
- node.js - Express 4+pug disable layout
- python - 如何按距离对地理点列表进行聚类?
- html - Flexbox 内容没有与链接和图像均匀分布
- python - 如何将混合类型列表更改为 str
- r - Xubuntu 16.04 上的 R 升级/安装
- shared-libraries - 如何理解 .so 文件中的不同部分,例如 .plt、.text?
- python-3.x - 使用 multiprocessing.Process 返回一个对象