Tom*_*lez 4 javascript events resolve node.js promise
我正在使用一个 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);
}
})
Run Code Online (Sandbox Code Playgroud)
承诺:
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
}
})
}
Run Code Online (Sandbox Code Playgroud)
首先让我们承诺制作:
function craft(elem){
//do whatever
return Promise((resolve,reject) =>
tf2.on('craftingComplete', (recipe,itemsGained) =>
if( recipe !== -1 ){
resolve(recipe, itemsGained);
}else{
reject("unsuccessful");
}
})
);
}
Run Code Online (Sandbox Code Playgroud)
因此,为了制作倍数,我们将数组映射到 promises 并使用 Promise.all:
Promise.all( array.map( craft ) )
.then(_=>"all done!")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8636 次 |
| 最近记录: |