如何在点击时执行几个承诺

时间:2018-12-19 16:44:18

标签: javascript

我正在尝试使用承诺创建游戏,并且仅在单击鼠标(上下)时调用它们,将游戏状态从第一个承诺(A)传递到最后一个(C),并进行更新。如果承诺B正确执行,则承诺C根本不执行。是否可以链接多个承诺并仅在事件触发时执行它们?

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))
})

2 个答案:

答案 0 :(得分:0)

您的承诺重新出现。它们需要在您的draw函数的范围内创建(并由这些函数返回),然后在回调中被解析,例如:

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只能解决一次,这引出了一个问题,即诺言是否甚至是您要实现的目标的正确模型。

答案 1 :(得分:-2)

这里有链接承诺的简短片段

var firstMethod = function() {
   var promise = new Promise(function(resolve, reject){
      setTimeout(function() {
         console.log('first method completed');
         resolve({data: '123'});
      }, 2000);
   });
   return promise;
};


var secondMethod = function(someStuff) {
   var promise = new Promise(function(resolve, reject){
      setTimeout(function() {
         console.log('second method completed');
         resolve({newData: someStuff.data + ' some more data'});
      }, 2000);
   });
   return promise;
};

var thirdMethod = function(someStuff) {
   var promise = new Promise(function(resolve, reject){
      setTimeout(function() {
         console.log('third method completed');
         resolve({result: someStuff.newData});
      }, 3000);
   });
   return promise;
};

firstMethod()
   .then(secondMethod)
   .then(thirdMethod);