ES6 Getter返回空对象

时间:2017-03-29 01:11:52

标签: javascript ecmascript-6 cloudinary

我创建了一种基于另一种方法抓取图像数据的方法。如您所见,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

1 个答案:

答案 0 :(得分:-1)

不确定,但在这里你可能会失去这种背景。

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

检查这个'仍然链接到您的UsersController对象