let event = (num) => Math.floor(Math.random() *num)>2 ? true : false
let timer = (num) => Math.floor(Math.random() * num)*1000
let condition = function(something,timer,num) {
return new Promise((resolve,reject)=>{
setTimeout(function(){
if(something) {
resolve('第'+ num +".成功了花了"+timer+'秒');
} else {
reject('第'+ num +'次失败QQ');
}
},timer)
})
}
//----------------------------只有一个非同步事件的情况----------------------------------
async function example() {
try{
const res1 = await condition(event(5),timer(5),1)
console.log('event1:',res1)
}
catch(err){
console.log('失败:',err)
}
}
//---------若是两个事件以上,只要其中一个出现错误,即进入catch的阶段,并不在继续往下执行-----------
async function example() {
try{
const res1 = await condition(event(5),timer(5),1)
console.log('event1:',res1)
const res2 = await condition(event(5),timer(5),2)
console.log('event2:',res2)
const res3 = await condition(event(5),timer(5),3)
console.log('event3:',res3)
}
catch(err){
console.log('失败:',err)
}
}
/*----------与 Promise.all() 搭配,在全部完成後才进行下一步,若事件都成功,则印出阵列回复,若其中rejected,.catch立即回传第一个完成的失败回复-----------*/
//-----与 Promise.race() 搭配,其中一事件先完成(不论成功与否),即进入对应的try...catch----------
async function example() {
try{
const res = await Promise.all([condition(event(5),timer(5),1),condition(event(5),timer(5),2),condition(event(5),timer(5),3),condition(event(5),timer(5),4)])
console.log(res)
}
catch(err){
console.log('失败:',err)
}
}
//----------------------------------------------------------------------------------
example()
<<: popcat 如何使用 python 搭配 selenium 在浏览器上自动点击
>>: 如何让 IIS 底下的 PHP 显示错误内容 (500 Error)
Case01 Controller [HttpPost] public IActionResult ...
最近补课的模式有了改变,大部分时间都是诗忆读着讲义,遇到问题或是想要学得更深入的时候再和唯心讨论。 ...
事件风暴 Event Storm 事件风暴 : 理解、访谈需求 目的 : 将商业流程视觉化,找出核心...
前言 各位早安,书接上回我们将程序码改得更方便阅读,还加上抓取连结的功能,今天我们要来把这些抓到的资...
算是检验自己对JavaScript理解一个很好的方法: 范例 : const cat1 = { na...