JSFiddle - React, Tailwind, and code Playground

by ysuper

HTML

<pre>
1:IT人員賽跑,都到才算完成。
2:IT人員接力賽跑 (promise)
3:IT人員賽跑,都到才算完成。(promise all)
</pre>

JavaScript

function race(p_array, callback) {
  var target = p_array.length;
  var peoples = [];

  function check(p) {
    peoples.push(p)
    if (peoples.length == target) {
      callback()
    }
  }
  p_array.forEach(function(f) {
    f(check);
  });
}

function p1(check) {
  return new Promise(function(resolve, reject) {
    window.setTimeout(function() {
      console.log('Ysuper 抵達')
      check('Ysuper')
    }, (Math.random() + 1) * 1000)
  })
}

function p2(check) {
  window.setTimeout(function() {
    console.log('Timmy 抵達')
    check('Timmy')
  }, (Math.random() + 1) * 1000)
}

function p3(check) {
  window.setTimeout(function() {
    console.log('Chiaying 抵達')
    check('Chiaying')
  }, (Math.random() + 1) * 1000)
}

function success() {
  console.log('IT 完成')
  console.log('-------')
}
///////////////////////////////////

function p4() {
  return new Promise(function(resolve,reject){
    window.setTimeout(function() {
      console.log('Ysuper 跑完')
      resolve('Ysuper')
    }, (Math.random() + 1) * 1000)
  })
}

function p5() {
  return new Promise(function(resolve,reject){
    window.setTimeout(function() {
      console.log('Timmy 跑完')
      resolve('Timmy')
    }, (Math.random() + 1) * 1000)
  })
}

function p6() {
  return new Promise(function(resolve,reject){
    window.setTimeout(function() {
      console.log('Chiaying 跑完')
      resolve('Chiaying')
    }, (Math.random() + 1) * 1000)
  })
}

// 1
/* race([p1, p2, p3], success).then() */

// 2
/* p4().then(p5).then(p6).then(function(){console.log('接力完成')})
Promise.all([funcA(), funcB(), funcC()])
       .then(function(){ console.log('上菜'); });
 */
 
 // 3
 Promise.all([p4(),p5(),p6()]).then(function(){console.log('The End')})