等待事件以解决承诺



我正在使用一个node.js模块,该模块具有没有回调的方法。取而代之的是,有一个在该方法完成时触发的事件。我想解决一个承诺,使用该事件作为回调,确保我该方法已成功完成。

array.lenght on promise可以是X。所以,我需要"听到"X次事件以确保我所有方法都成功完成<-这不是问题,我只是告诉你我知道这可能会发生

事件:

tf2.on('craftingComplete', function(recipe, itemsGained){
  if(recipe == -1){
  console.log('CRAFT FAILED')
  }
  else{
        countOfCraft++;
    console.log('Craft completed! Got a new Item  #'+itemsGained);
  }
})

承诺:

const craftWepsByClass = function(array, heroClass){
        return new Promise(function (resolve, reject){
            if(array.length < 2){
                console.log('Done crafting weps of '+heroClass);
                return resolve();
            }
            else{
                for (var i = 0; i < array.length; i+=2) {
                    tf2.craft([array[i].id, array[i+1].id]); // <--- this is the module method witouth callback
                }
        return resolve(); // <---- I want resolve this, when all tf2.craft() has been completed. I need 'hear' event many times as array.length
            }   
        })
}

首先让我们承诺制作:

function craft(elem){
 //do whatever
 return Promise((resolve,reject) => 
  tf2.on('craftingComplete', (recipe,itemsGained) => 
   if( recipe !== -1 ){
     resolve(recipe, itemsGained);
   }else{
    reject("unsuccessful");
   }
  })
);
}

因此,为了制作倍数,我们将数组映射到 promise 并使用 Promise.all:

Promise.all( array.map( craft ) )
 .then(_=>"all done!")

如果事件的触发顺序与导致它们的相应craft()调用的顺序相同,则可以使用队列:

var queue = []; // for the tf2 instance
function getNextTf2Event() {
  return new Promise(resolve => {
    queue.push(resolve);
  });
}
tf2.on('craftingComplete', function(recipe, itemsGained) {
  var resolve = queue.shift();
  if (recipe == -1) {
    resolve(Promise.reject(new Error('CRAFT FAILED')));
  } else {
    resolve(itemsGained);
  }
});
function craftWepsByClass(array, heroClass) {
  var promises = [];
  for (var i = 1; i < array.length; i += 2) {
    promises.push(getNextTf2Event().then(itemsGained => {
      console.log('Craft completed! Got a new Item  #'+itemsGained);
      // return itemsGained;
    }));
    tf2.craft([array[i-1].id, array[i].id]);
  }
  return Promise.all(promises).then(allItemsGained => {
    console.log('Done crafting weps of '+heroClass);
    return …;
  });
}

如果您对事件的顺序一无所知,并且可能有多个并发调用来craftWepsByClass,则无法避免全局计数器(即链接到tf2实例的计数器)。缺点是,例如,在两个重叠的调用中a = craftWepsByClass(…), b = craftWepsByClass()在第二个调用的所有制作完成之前,a承诺不会得到解决。

var waiting = []; // for the tf2 instance
var runningCraftings = 0;
tf2.on('craftingComplete', function(recipe, itemsGained) {
  if (--runningCraftings == 0) {
    for (var resolve of waiting) {
      resolve();
    }
    waiting.length = 0;
  }
  if (recipe == -1) {
    console.log('CRAFT FAILED')
  } else {
    console.log('Craft completed! Got a new Item  #'+itemsGained);
  }
});
function craftWepsByClass(array, heroClass) {
  for (var i = 1; i < array.length; i += 2) {
    runningCraftings++;
    tf2.craft([array[i-1].id, array[i].id]);
  }
  return (runningCraftings == 0
    ? Promise.resolve()
    : new Promise(resolve => {
        waiting.push(resolve);
      })
  ).then(() => {
    console.log('Done crafting weps of '+heroClass);
  });
}

当然,在这两种解决方案中,您必须 100% 确定每次调用craft()只会导致一个事件。

您可以查看event-as-promise包。它会不断将事件转换为承诺,直到您完成所有事件处理。

当与async/await结合使用时,您可以使用事件轻松编写for循环或while循环。例如,我们希望处理data事件,直到它返回null

const eventAsPromise = new EventAsPromise();
emitter.on('data', eventAsPromise.eventListener);
let done;
while (!done) {
  const result = await eventAsPromise.upcoming();
  // Some code to process the event result
  process(result);
  // Mark done when no more results
  done = !result;
}
emitter.removeListener('data', eventAsPromise.eventListener);

如果您精通生成器功能,那么看起来可能会更简单一些。

const eventAsPromise = new EventAsPromise();
emitter.on('data', eventAsPromise.eventListener);
for (let promise of eventAsPromise) {
  const result = await promise;
  // Some code to process the event result
  process(result);
  // Stop when no more results
  if (!result) {
    break;
  }
}
emitter.removeListener('data', eventAsPromise.eventListener);

我需要检查事件"制作完成"是否已经触发了很多次,因为我 致电 tf2.craft。任何可能的ID或工艺是否失败都无关紧要。 我需要知道 tf2.craft 是否已完成,只有为什么要检查 "制作完成"活动

鉴于我们知道循环中的i for将递增i += 2 i小于array.length,我们可以在for循环之前创建一个等于该数字的变量,并将i与事件处理程序中的数字进行比较

const craftWepsByClass = function(array, heroClass) {
  return new Promise(function(resolve, reject) {
    var countCraft = 0;
    var j = 0;
    var n = 0;
    for (; n < array.length; n += 2);
    tf2.on('craftingComplete', function(recipe, itemsGained) {
      if (recipe == -1) {
        console.log('CRAFT FAILED')
      } else {
        countOfCraft++;
        console.log('Craft completed! Got a new Item  #' + itemsGained);
        if (j === n) {
          resolve(["complete", craftCount])
        }
      }
    })
    if (array.length < 2) {
      console.log('Done crafting weps of ' + heroClass);
      return resolve();
    } else {
      try {
        for (var i = 0; i < array.length; i += 2, j += 2) {
          tf2.craft([array[i].id, array[i + 1].id]);
        }
      } catch (err) {
        console.error("catch", err);
        throw err
      }
    }
  })
}
craftWepsByClass(array, heroClass)
.then(function(data) {
  console.log(data[0], data[1])
})
.catch(function(err) {
  console.error(".catch", err)
})

最新更新