

适用于 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-callback-function"></a>

创建 `AWS.Request` 对象的各个服务对象方法可以接受匿名回调函数作为最后一个参数。此回调函数的签名为：

```
function(error, data) {
    // callback handling code
}
```

此回调函数在返回成功响应或错误数据时执行。如果方法调用成功，则响应的内容在 `data` 参数中供回调函数使用。如果调用不成功，则在 `error` 参数中提供有关失败的详细信息。

通常，回调函数内部的代码经过了错误测试，在返回错误时会进行处理。如果未返回错误，则代码从 `data` 参数检索响应中的数据。回调函数的基本格式如此例中所示。

```
function(error, data) {
    if (error) {
        // error handling code
        console.log(error);
    } else {
        // data handling code
        console.log(data);
    }
}
```

在以上示例中，错误的详细信息或者返回的数据记录到控制台中。此处的示例演示了作为对服务对象调用方法的一部分传递的回调函数。

```
new AWS.EC2({apiVersion: '2014-10-01'}).describeInstances(function(error, data) {
  if (error) {
    console.log(error); // an error occurred
  } else {
    console.log(data); // request succeeded
  }
});
```

## 访问请求和响应对象
<a name="access-request-response"></a>

在回调函数内部，对于大多数服务，JavaScript 关键字 `this` 是指底层 `AWS.Response` 对象。在以下示例中，`httpResponse` 对象的 `AWS.Response` 属性在回调函数中用于记录原始响应数据和标头，以帮助调试。

```
new AWS.EC2({apiVersion: '2014-10-01'}).describeInstances(function(error, data) {
  if (error) {
    console.log(error); // an error occurred
    // Using this keyword to access AWS.Response object and properties
    console.log("Response data and headers: " + JSON.stringify(this.httpResponse));
  } else {
    console.log(data); // request succeeded
  }
});
```

此外，由于 `AWS.Response` 对象具有一个 `Request` 属性，其中包含由原始方法调用发送的 `AWS.Request`，您还可以访问所发出请求的详细信息。