Ember CLI/Ember.js中的承诺



我正在尝试编写一个ember-cli部署插件,并且可以在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));

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

最新更新