首页 > 解决方案 > 如何在点击时执行多个承诺

问题描述

我正在尝试使用 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))
})

标签: javascript

解决方案


你的承诺是背对面的。它们需要在您的绘图函数范围内创建(并由这些函数返回),然后在回调中解析,例如:

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 是否甚至是您要实现的目标的正确模型。


推荐阅读