Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[js]使一个返回Promise的函数同时支持Error-first回调形式与Promise调用方式。 #25

Open
Jiasm opened this issue Apr 14, 2018 · 3 comments

Comments

@Jiasm
Copy link
Member

Jiasm commented Apr 14, 2018

使函数同时支持两种调用方法:

function pro(a, b) {
  return new Promise((resolve, reject) => {
    resolve(a + b)
  })
}

function wrap(func) {
  // code here
}

let func = wrap(pro)

func(1, 2, (err, result) => {
  if (err) {
    console.error(err)
  } else {
    console.log(result)
  }
})

func(1, 2).then(console.log, console.error)
@VaJoy
Copy link
Member

VaJoy commented Apr 14, 2018

欢迎出题,捧场下了

    function pro(a, b) {
      return new Promise((resolve, reject) => {
            reject(a + b)
      })
    }

    function wrap(func) {
      let argNum = func.length;
      return function result(...args){
        let pm = func.apply(null, args);
        let efCallback = args[argNum];
        if(typeof efCallback === 'function'){
          pm.then(data=>{
            efCallback(null, data)
          }).catch(err=>{
            efCallback(err)
          })
        } else {
          return pm
        }
      }
    }

    let func = wrap(pro)

    func(1, 2, (err, result) => {
      if (err) {
        console.error(err)
      } else {
        console.log(result)
    }
    })

    func(1, 2).then(console.log, console.error)

@Jiasm
Copy link
Member Author

Jiasm commented Apr 14, 2018

因为示例中并没有用到reject,所以函数签名仅写了一个,我来修改一下。

@VaJoy
Copy link
Member

VaJoy commented Apr 14, 2018

@Jiasm 嗯嗯,刚刚看走眼了以为只有一个参数会有问题囧。
我帮你去群里宣传下,多喊些人来

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants