0

I'm trying to write a ember-cli-deploy plugin and can really use some help with promises. In my index.js for the main plugin, I have the following code index.js:

prepare: function(context) {
    ...
    ...
    var awsDeploymentOptions = {....};
    this._awsCodeDeployClient = new CodeDeployClient({awsDeploymentOptions: awsDeploymentOptions});

}
upload: function() {
    ...
    ...
    var uploadPromise = (awsDeploymentOptions.revision.revisionType === 'S3') ? this._awsS3Client.upload(filesToUpload, this.readConfig('s3UploadOptions')) : new Promise().resolve();
    return uploadPromise.then(function(result){return this._awsCodeDeployClient.createDeployment(result)}.bind(this));
}

The above works as expected and the promises get resolved properly.

If I change the above code to:

return uploadPromise.then(this._awsCodeDeployClient.createDeployment);

the code fails. Then, I tried the following, which fails as well:

return uploadPromise.then(this._awsCodeDeployClient.createDeployment.bind(this));

In both the cases above, it complains of undefined variables/properties inside createDeployment method, which is defined as below:

createDeployment: function(s3FileUploadOptions) {
    return new Promise(function(resolve, reject) {
        //This is where the problem lies. this is never resolved
        //to this module's 'this' and I cannot access this.deploymentOptions
        //Any reference to 'this' variable causes an error
        var awsDeploymentOptions = this.awsDeploymentOptions;
        this.codeDeploy.createDeployment(this.awsDeploymentOptions, function(error, data) {
            if (error)
                reject(error); // an error occurred
            else resolve({awsDeploymentId:data.deploymentId}); // successful response. Return deployment Id
        }.bind(this));
    }.bind(this));
}

What am I doing wrong in the two scenarios above?

MojoJojo
  • 3,897
  • 4
  • 28
  • 54
  • Could you please: a) indent your code properly, and b) reduce it to the part that is relevant to your question? I'm pretty sure all that AWS code is irrelevant noise. – Tomalak Jan 08 '16 at 08:19
  • try this. var that = this; return uploadPromise.then(this._awsCodeDeployClient.createDeployment.bind(that)); – blessanm86 Jan 08 '16 at 11:52

1 Answers1

1

How about this?

return uploadPromise.then(result => this._awsCodeDeployClient.createDeployment(result));

Arrow functions keep the scope from the calling context.

uberclops
  • 161
  • 5