回调内容怎么传给调用的方法里处理?
发布于 9 天前 作者 liygheart 140 次浏览 来自 问答

想不出怎么描述了,有点绕 下面是我碰到的问题: 七牛nodejs版的demo:

exports.uploadFile = function(key, localFile) {
  uptoken = uptoken(bucket, key);
  var extra = new qiniu.io.PutExtra();
  qiniu.io.putFile(uptoken, key, localFile, extra, function(err, ret) {
    if(!err) {
      // 上传成功, 处理返回值
      console.log(ret.hash, ret.key, ret.persistentId);
    } else {
      // 上传失败, 处理返回代码
      console.log(err);
    }
  });
};

调用:

var qiniu = require("./utils/qiniuupload");
qiniu.uploadFile("aaaa.jpg", "/Users/xxxx/Pictures/404.jpg");

我想把uploadFile方法里调用putFile方法里的回调内容放在调用里处理,就是下面这种情况 改过之后的uploadFile()方法

exports.uploadFile = function(key, localFile, cb) {
  uptoken = uptoken(bucket, key);
  var extra = new qiniu.io.PutExtra();
  qiniu.io.putFile(uptoken, key, localFile, extra, function (err, ret) {
    cb(err, ret);
  });
};

调用

qiniuupload.uploadFile(Date.now() + "." + uploadFile.type.split("/")[1], filePath, function (err, ret) {
      if(err) {
        console.log(err);
      } else {
        console.log(ret.hash, ret.key, ret.persistentId);
        res.render("index", {
          avatar: "http://xxxx.qiniucdn.com/" + ret.key
        });
      }
    });

启动服务的时候报错

TypeError: cb is not a function

求解

4 回复

异步调用,cb已经被释放了

这样改试试: exports.uploadFile = function(key, localFile, cb) { uptoken = uptoken(bucket, key); var extra = new qiniu.io.PutExtra(); qiniu.io.putFile( uptoken, key, localFile, extra, (function(cb){ return function (err, ret) { cb(err, ret); } })(cb) ); };

exports.uploadFile = function(key, localFile, cb) { uptoken = uptoken(bucket, key); var extra = new qiniu.io.PutExtra(); qiniu.io.putFile( uptoken, key, localFile, extra, (function(cb){ return function (err, ret) {cb(err, ret);} })(cb) ); };

@gendemos 不行,还是报错

TypeError: cb is not a function
回到顶部