使用Johnny-five via Nodejs操作 arduino uno 并进行promise化

maomaoamaomao
const { Board, Led } = require("johnny-five");
const board = new Board();

// callback way
/* const fader = led => {
  led.fadeIn(500, () => {
    led.fadeOut(null, () => fader(led))
  }); */

// Promisify他!

const fadeOutPromise = led => new Promise(resolve => {
  led.fadeOut(null, () => resolve('fadeOut finish'))
})

const fadeInPromise = led => new Promise(resolve => led.fadeIn(500, () => resolve('fadeIn finish')))


const fader = () => {
  let counter = 0
  return cycle = (led) =>
    fadeInPromise(led)
      .then(res => { console.log(res); return fadeOutPromise(led) })
      .then(console.log)
      .then(() => console.log('finish cycle'))
      .then(() => console.log(`total count:${++counter}`))
      .then(() => cycle(led))
}


board.on("ready", () => {
  const led = new Led(11);
  console.log('start')
  const cycle = fader()
  cycle(led)
});

把callback改为回调就舒服多了。也解决了回调地狱的问题,但是就要经过一次promisify的过程,这个时间花的绝对是物超所值的

阅读 225
13 声望
0 粉丝
0 条评论
13 声望
0 粉丝
文章目录
宣传栏