0

我正在尝试编写一个 ember-cli-deploy 插件,并且确实可以在承诺方面使用一些帮助。在主插件的 index.js 中,我有以下代码 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));
}

上述工作按预期工作,并且承诺得到正确解决。

如果我将上面的代码更改为:

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

代码失败。然后,我尝试了以下方法,但也失败了:

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

在上述两种情况下,它都会抱怨 createDeployment 方法中未定义的变量/属性,定义如下:

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));
}

在上述两种情况下我做错了什么?

4

1 回答 1

1

这个怎么样?

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

箭头函数使作用域远离调用上下文。

于 2016-01-11T12:26:06.867 回答