1.0.1 • Published 2 years ago

w-order-js v1.0.1

Weekly downloads
-
License
ISC
Repository
-
Last release
2 years ago

注意

此包未经过严格的BUG审查,请勿用于重要的项目。

项目地址:https://gitee.com/laowans/order-js.git

如果觉得该思路不错,可以下载源码,进行定制化改造

前言

我们学习 js 应该或多或少听过回调地狱,就是函数的执行依赖上一个函数处理结果。

比如这样:

const process = (msg, next) => {
  setTimeout(() => {
    console.log(msg)
    next && next()
  }, 1000)
}
process('msg_1', () => {
  process('msg_2', () => {
    process('msg_3', () => {
      process('msg_4', () => {
          console.log('end')
        })
    })
  })
})

下一个函数的执行必须等上一个函数执行完毕,非常不利于代码的维护和阅读,而这个包就是为了解决这个问题的

使用

案例:

const order = require('w-order-js')

const process = (next, s) => {
    setTimeout(() => {
        console.log('msg_' + s)
        next(s+1)
    }, 1000)
}
const or = new order(1)

or.then(process)
.then(process)
.then(process)
.then(process)
.end(()=>{
    console.log('end');
})

参数

// order:new order传入的值(可以多个),将作为第一个.then() 的参数
const or = new order(1, [1, 2])

/* 
    .then: 接受一个或两个函数作为参数:(fn1, hn2)
*/
or.then((next, value1, value2, ……, valuen)=>{
    /* 
        fn1:为处理函数,接受一个或得多个参数
        参数:
            第一个参数 next 为一个函数,作为通行证,调用该函数,视为该过程完成,将执行下一个 .then,同时还可以传入参数,参数作为下一个 .then 第一个函数参数的参数
            后面的参数为 new order 传入的参数或是上一个 .then 调用 next 传入的参数,next 后面的参数的多少,取决于传入的参数的多少
            注意:next 在此函数内必须调用,不然将破坏顺序调用完整性
    */
},(error, next, value1, value2, ……, valuen)=>{
    /* 
        fn2:为错误处理函数,当 fn1 的代码出现错误调用此函数,接受两个或得多个参数
        参数:
            第一个参数 error 为错误对象
            第二个参数 next 和上面的 next 是一样的(可以不调用)
            后面的参数为 new order 传入的参数或是上一个 .then 调用 next 传入的参数,next 后面的参数的多少,取决于传入的参数的多少
            注意:异步错误不能捕获
    */
})

/* 
    .end:为结束函数(注意必须调用此函数,表示顺序调用的结束)
    参数:
        接受一个函数作为参数,该函数接受的参数上一个 .then 调用 next 传入的参数
*/
.end((value1, value2, ……, valuen)=>{
    
})

/* 
    .catch:为全局错误处理函数,当顺序调用过程中出现错误就会调用传入的函数,此函数接受一个函数作为参数,该函数接受一个 error 错误对象
    注意:
        .catch多次调用,只会已最后一次调用传入的函数,作为错误处理函数
        异步错误不能捕获
*/
.catch((err)=>{
    console.log(err.message);
})