我正在尝试编写一个ember-cli-deploy插件,并且可以在promises中使用一些帮助。在我的主插件的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));
}
上述两种情况我做错了什么?
答案 0 :(得分:1)
这个怎么样?
return uploadPromise.then(result => this._awsCodeDeployClient.createDeployment(result));
Arrow functions将范围与调用上下文保持一致。