[英]Promises in Ember CLI/Ember.js
我正在嘗試編寫ember-cli-deploy插件,並且確實可以在Promise中使用一些幫助。 在主插件的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));
}
在上述兩種情況下,我在做什么錯?
這個怎么樣?
return uploadPromise.then(result => this._awsCodeDeployClient.createDeployment(result));
箭頭函數使作用域不受調用上下文的影響。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.