This question already has answers here:
How do I convert an existing callback API to promises?
                                
                                    (20个答案)
                                
                        
                                4年前关闭。
            
                    
我正在尝试将此简单函数转换为Promise。我认为解析将代替返回function(err, value)的回调。我在这里想念什么?

var retrieveSet = function(offset){
  var opts = {}
  opts.limit = 100
  if(offset) opts.offset = offset
  return new Promise(function (resolve, reject) {
    chargebee.subscription
    .list(opts)
    .request(resolve);
  })
}


retrieveSet().then(function(data){
  console.log(data)
}).catch(function(e){
  throw e
})

最佳答案

var retrieveSet = function(offset){
  var opts = {}
  opts.limit = 100
  if(offset) opts.offset = offset
  return new Promise(function(resolve, reject) {
    chargebee.subscription
    .list(opts)
    .request(function(err, value){
      if(err) return reject(err)
      return resolve(value)
    })
  })
}

关于javascript - 从带有错误,值签名的回调中创建 promise ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28547192/

10-13 03:32