我正在使用一个 node.js 模块,它有一个没有回调的方法。取而代之的是,有一个事件在该方法完成时触发。我想要解决一个 promise ,使用该事件作为回调确保我该方法已成功完成。
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);
}
})
promise :
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
}
})
}
最佳答案
首先让我们 promise 制作:
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!")
关于javascript - 等待一个事件来解决一个 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46817981/