Page's Personal Website

Promise实现递归调用

2020-03-16

[TOC]

想要做一个简单的AI,实现一个动作序列,等前面一个执行完毕了,再执行下一个动作

Promise&then

参考我自己的一篇帖子,记录了我自己理解promise&then的[1]

实现

直接上代码了

var dramas = [
 {
  "time": 2000,
  "func": function(sec){
  
   console.log('function 1', new Date().toLocaleString());
   return new Promise(resolve => {
    // console.log(`1 waiting ${sec}s...`, new Date().toLocaleString());
    setTimeout(() => resolve(1), sec);
   });
  },
 },
	
 {
  "time": 3000,
  "func": function(sec){
  
   console.log('function 2', new Date().toLocaleString());
   return new Promise(resolve => {
    // console.log(`2 waiting ${sec}s...`, new Date().toLocaleString());
    setTimeout(() => resolve(2), sec);
   });
  },
 },
]

function doDrama(listDrama, index) {
  return new Promise((resolve, reject) => {
    if(index >= listDrama.length) {
      return resolve({ done: true, data: "done"});
    } else {
      return resolve({ done: false });
    }
  })
  .then(res => {
    if(res.done) {
      return Promise.resolve(res.data); 
    } else {
   return listDrama[index].func(listDrama[index].time).then(()=>{
    doDrama(listDrama, index+1);
   })
    }
  });
}

doDrama(dramas, 0).then(res=>{
 console.log('done.'))
})

参考

[1]Promise.then链式调用顺序

[2]Promise怎么实现递归


Comments

Content