

适用于 JavaScript 的 AWS SDK v2 已终止支持。建议您迁移到 [适用于 JavaScript 的 AWS SDK v3](https://docs.aws.amazon.com//sdk-for-javascript/v3/developer-guide/)。有关更多详情和如何迁移的信息，请参阅本[公告](https://aws.amazon.com/blogs//developer/announcing-end-of-support-for-aws-sdk-for-javascript-v2/)。

# 使用请求对象事件侦听器
<a name="using-a-response-event-handler"></a>

在调用服务对象方法时，如果您未创建并将匿名回调函数作为参数传递，则方法调用生成 `AWS.Request` 对象，该对象必须使用其 `send` 方法手动设置。

要处理响应，您必须为 `AWS.Request` 对象创建一个事件侦听器，以便为方法调用注册回调函数。以下示例演示如何创建 `AWS.Request` 对象用于调用服务对象方法，以及创建针对成功返回的事件侦听器。

```
// create the AWS.Request object
var request = new AWS.EC2({apiVersion: '2014-10-01'}).describeInstances();

// register a callback event handler
request.on('success', function(response) {
  // log the successful data response
  console.log(response.data); 
});

// send the request
request.send();
```

在调用了 `send` 上的 `AWS.Request` 方法之后，当服务对象收到 `AWS.Response` 对象时，事件处理程序执行。

有关 `AWS.Request` 对象的更多信息，请参阅 API 参考中的 [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Request.html](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Request.html)。有关 `AWS.Response` 对象的更多信息，请参阅[使用响应对象](the-response-object.md)或 API 参考中的 [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Response.html](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Response.html)。

## 链接多个回调
<a name="response-chaining-callbacks"></a>

您可在任何请求对象上注册多个回调。可以为不同事件或相同事件注册多个回调。此外，您可以按下例中所示链接多个回调。

```
request.
  on('success', function(response) {
    console.log("Success!");
  }).
  on('error', function(response) {
    console.log("Error!");
  }).
  on('complete', function() {
    console.log("Always!");
  }).
  send();
```

## 请求对象完成事件
<a name="request-object-completion-events"></a>

`AWS.Request` 对象根据各个服务操作方法的响应引发这些完成事件：
+ `success`
+ `error`
+ `complete`

您可以注册回调函数以响应任意这些事件。有关所有请求对象事件的完整列表，请参阅 API 参考中的 [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Request.html](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Request.html)。

### success 事件
<a name="request-success-event"></a>

从服务对象收到成功响应时引发 `success` 事件。下面说明您如何为此事件注册回调函数。

```
request.on('success', function(response) { 
  // event handler code
});
```

该响应提供 `data` 属性，其中包含来自服务的序列化响应数据。例如，以下内容调用 Amazon S3 服务对象的 `listBuckets` 方法

```
s3.listBuckets.on('success', function(response) {
  console.log(response.data);
}).send();
```

返回响应，然后将以下 `data` 属性内容输出到控制台。

```
{ Owner: { ID: '...', DisplayName: '...' },
  Buckets: 
   [ { Name: 'someBucketName', CreationDate: someCreationDate },
     { Name: 'otherBucketName', CreationDate: otherCreationDate } ],
  RequestId: '...' }
```

### error 事件
<a name="request-error-event"></a>

从服务对象收到出错响应时引发 `error` 事件。下面说明您如何为此事件注册回调函数。

```
request.on('error', function(error, response) { 
  // event handling code
});
```

引发 `error` 事件时，响应的 `data` 属性的值为 `null`，`error` 属性包含错误数据。关联的 `error` 对象作为第一个参数传递到注册的回调函数。例如，以下代码：

```
s3.config.credentials.accessKeyId = 'invalid';
s3.listBuckets().on('error', function(error, response) {
  console.log(error);
}).send();
```

返回错误，然后将以下错误数据输出到控制台。

```
{ code: 'Forbidden', message: null }
```

### complete 事件
<a name="request-complete-event"></a>

服务对象调用完成时将引发 `complete` 事件，而不论调用结果为成功还是失败。下面说明您如何为此事件注册回调函数。

```
request.on('complete', function(response) { 
  // event handler code
});
```

使用 `complete` 事件回调来处理不论成功还是出错均必须执行的任何请求清理。如果您在 `complete` 事件的回调中使用响应数据，请先检查 `response.data` 或 `response.error` 属性，然后尝试访问任意一个属性，如下例中所示。

```
request.on('complete', function(response) {
  if (response.error) {
    // an error occurred, handle it
  } else {
    // we can use response.data here
  }
}).send();
```

## 请求对象 HTTP 事件
<a name="request-object-http-events"></a>

`AWS.Request` 对象根据各个服务操作方法的响应引发这些 HTTP 事件：
+ `httpHeaders`
+ `httpData`
+ `httpUploadProgress`
+ `httpDownloadProgress`
+ `httpError`
+ `httpDone`

您可以注册回调函数以响应任意这些事件。有关所有请求对象事件的完整列表，请参阅 API 参考中的 [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Request.html](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Request.html)。

### httpHeaders 事件
<a name="request-httpheaders-event"></a>

当远程服务器发送标头时，将引发 `httpHeaders` 事件。下面说明您如何为此事件注册回调函数。

```
request.on('httpHeaders', function(statusCode, headers, response) {
  // event handling code
});
```

传递到回调函数的 `statusCode` 参数是 HTTP 状态代码。`headers` 参数包含响应标头。

### httpData 事件
<a name="request-httpdata-event"></a>

引发 `httpData` 事件用于流式传输来自服务的响应数据包。下面说明您如何为此事件注册回调函数。

```
request.on('httpData', function(chunk, response) {
  // event handling code
});
```

此事件通常在不适合将整个响应加载到内存中时，用于分块接收较大的响应。此事件具有额外的 `chunk` 参数，其中包含来自服务器的实际数据的一部分。

如果您为 `httpData` 事件注册回调，则响应的 `data` 属性包含请求的整个序列化输出。如果您没有用于内置处理程序的额外解析和内存开销，则必须删除默认 `httpData` 侦听器。

### httpUploadProgress 和 httpDownloadProgress 事件
<a name="request-httpupload-download-progress-event"></a>

HTTP 请求上传了更多数据时将引发 `httpUploadProgress` 事件。与此类似，HTTP 请求下载了更多数据时将引发 `httpDownloadProgress` 事件。下面说明您如何为这些事件注册回调函数。

```
request.on('httpUploadProgress', function(progress, response) {
  // event handling code
})
.on('httpDownloadProgress', function(progress, response) {
  // event handling code
});
```

传递到回调函数的 `progress` 参数包含一个对象，该对象保存请求的已加载字节数和总字节数。

### httpError 事件
<a name="request-httperror-event"></a>

HTTP 请求失败时将引发 `httpError` 事件。下面说明您如何为此事件注册回调函数。

```
request.on('httpError', function(error, response) {
  // event handling code
});
```

传递到回调函数的 `error` 参数包含所引发的错误。

### httpDone 事件
<a name="request-httpdone-event"></a>

服务器完成数据发送时将引发 `httpDone` 事件。下面说明您如何为此事件注册回调函数。

```
request.on('httpDone', function(response) {
  // event handling code
});
```