【问题标题】:ES6 Getter returning empty objectES6 Getter 返回空对象
【发布时间】:2017-03-29 09:39:08
【问题描述】:

我创建了一个基于另一种方法抓取图像数据的方法。如您所见,uploadAvatar() 方法将对象从 Cloudinary 存储回构造函数对象this._userImage;。然后我的getUserImage() 方法应该返回用户图像数据,但是当我将它记录到控制台时它返回{}:P。

ImageUploader.js

'use strict';

const cloudinary = require('cloudinary');

class ImageUploader {

  constructor(imageObj) {
    this.imageObj = imageObj;
    this._apiKey = "key";
    this._apiSecret = "secret";
    this.config = cloudinary.config({
      cloud_name: 'name',
      api_key: this._apiKey,
      api_secret: this._apiSecret
    });
    this._userImage = {}; // where user image object should be stored
  }


  * uploadAvatar(path) {
    cloudinary.uploader.upload(path, (data) => {
      this._userImage = data; // where I overwrite the constructor obj
    });
  }
  getUserImage() {
    return this._userImage; // this returns `{}` when I log it in UsersController.js
  }


}

module.exports = ImageUploader;

UsersController.js

'use strict'

const Validator = require("../Helpers/ValidatorHelper.js");
const ImageUploader = require("../Helpers/ImageUploader.js");

class UsersController {

  * registerView (request, response) {
    yield response.sendView('users.register');
  }

  * register (request, response) {
    const user = request.only('display_name', 'username', 'email', 'password', 'confirm_password', 'console');
    var avatar = request.file('avatar');

    let validator = new Validator(user, avatar);
    let imageUpload = new ImageUploader(avatar);

    let avatarStatus = yield validator.validateAvatar();
    var img;
    if (avatarStatus) { // is true
      yield imageUpload.uploadAvatar(avatar.file.path);
    } else { // is false
      // pick a random avatar
    }
    console.log(imageUpload.getUserImage());
    return response.status(200).json({
      user: user,
      avatar: imageUpload.getUserImage()
    });

  }


}

module.exports = UsersController

【问题讨论】:

  • 为什么uploadAvatar是一个没有yield的生成器? - 另外,您的代码中没有getter
  • yield imageUpload.uploadAvatar(avatar.file.path); 我试着让它成为一个吸气剂,但仍然给了我一个空对象。
  • 我再说一遍......为什么uploadAvatar 是一个生成器——在被称为uploadAvatar 的函数范围内没有yield——对我来说,这没有任何意义。
  • 所以这就是我的对象返回空的原因?

标签: javascript ecmascript-6 cloudinary


【解决方案1】:

不确定,但在这里你可能会丢失你的上下文。

cloudinary.uploader.upload(path, (data) => {
     this._userImage = data; // where I overwrite the constructor obj
});

检查“this”是否仍然链接到您的 UsersController 对象

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-07-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-26
  • 2018-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多