javascript - 如何在点击时执行多个承诺
问题描述
我正在尝试使用 Promise 制作游戏,并且仅在鼠标单击(向下和向上)时调用它们,将游戏状态从第一个 Promise (A) 传递到最后一个 Promise (C),并对其进行更新。如果 Promise B 正确执行,则 Promise C 根本不会执行。是否可以链接多个 Promise 并仅在事件触发时执行它们?
class A {
static draw() {
return new Promise((resolve) => {
const state = {name: 'Alex'};
resolve(state);
})
}
}
class B {
static draw(state) {
const div = document.querySelector('.app');
div.addEventListener('mousedown', () => {
return new Promise((resolve) => {
state.lastname = 'Johnson';
console.log('state with ln ' + state)
resolve(state);
})
})
}
}
class C {
static draw(state) {
const div = document.querySelector('.app');
div.addEventListener('mouseup', () => {
return new Promise((resolve) => {
state.age = '23';
console.log('state with age ' + state)
resolve(state);
})
})
}
}
A.draw()
.then(res => {
B.draw(res)
.then(res => C.draw(res))
})
解决方案
你的承诺是背对面的。它们需要在您的绘图函数范围内创建(并由这些函数返回),然后在回调中解析,例如:
class B {
static draw(state) {
const div = document.querySelector('.app');
return new Promise((resolve) => {
div.addEventListener('mousedown', () => {
state.lastname = 'Johnson';
console.log('state with ln ' + state)
resolve(state);
});
});
}
}
但是,这样的 Promise 只能解决一次,这就引出了一个问题,即 Promise 是否甚至是您要实现的目标的正确模型。
推荐阅读
- javascript - Paypal 按钮 - 在弹出窗口打开之前添加操作
- python - 使用 pip 安装时将 python 脚本添加到 PATH 环境变量
- python - pyInstaller 仅构建可执行文件
- hadoop - Apache Pig:将嵌套包合并为一个包
- c++ - 如何在引用上设置数据断点
- reactjs - 如何更改材料 ui 日期选择器语言和默认时区?
- java - 活动中未显示底部导航栏
- python-3.x - 试图从 OptionMenu 中选择选项以使用 tkinter 在嵌套字典中获取多个字典值
- php - MySQL DB 查询抛出错误,说我有语法错误。好像找不到他们?我相信它在查询的列部分
- pyspark - 如何在不使用 StandardScaler 的情况下标准化 PySpark 中的列?