# [Cloud](/miniprogram/dev/wxcloudservice/wxcloud/reference-sdk-api/Cloud).callFunction(object: Object): Promise<Object>

> 支持端：[小程序](/miniprogram/dev/framework/client-lib/version.md), [云函数](/miniprogram/dev/wxcloudservice/wxcloud/reference/changelog-server-sdk)

调用云函数

## 参数

### object: Object

| 属性 | 类型 | 默认值 | 必填 | 说明 |
| ---- | ---- | ------ | -------- | ---- |
| name | string |  | 是 | 云函数名 |
| data | Object |  | 否 | 传递给云函数的参数，在云函数中可通过 `event` 参数获取 |
| config | Object |  | 否 | 配置 |

**object.config 的结构**

| 属性 | 类型 | 默认值 | 必填 | 说明 |
| ---- | ---- | ------ | -------- | ---- |
| env | string |  | 是 | 环境 ID，填写后将忽略 init 时指定的环境 ID |

## 返回值

### Promise.<Object>

| 属性 | 类型 | 说明 |
| ---- | ---- | ---- |
| result  | any | 云函数返回的结果 |
| requestID  | string | 云函数执行 ID，可用于日志查询 |

## data 参数说明

如果 data 中包含大数据字段（建议临界值 100KB），建议使用 [`wx.cloud.CDN`](/miniprogram/dev/wxcloudservice/wxcloud/reference-sdk-api/utils/Cloud.CDN) 标记大数据字段，标记后在调用云函数时，该字段的内容将会上传至临时 CDN，然后在云函数中接收到的该字段值将是 CDN url，可在云函数中下载访问。通过这种方式，可以避免大数据传输造成的性能问题、及避免触及调用链路的传输大小限制。

如果在 `data` 中如果传入了 `Buffer` 类型的数据，数据在 JSON 序列化的过程中会被转成 `{ "type": "Buffer", data: number[] }` 的格式，以小程序端调用为例：

```js
// 小程序端调用
wx.cloud.callFunction({
  // ...
  data: {
    buf: ArrayBuffer // 此处填入了某种方式获取得到的 Buffer 数据，可以是 request 下来的，可以是读文件读出来的等等
  },
})
// 云函数端收到的 event 参数的结构：
{
  "type": "Buffer",
  "data": [ 17, 371, 255, ... ] // Uint8 Array
}
```

因此应当避免传入 `Buffer` 类型的数据，因为会让数据体积增大，增加传输耗时，如果需要传递 `Buffer`，有两种替代的建议方式：

1. 若 `Buffer` 较大，可使用 [`wx.cloud.CDN`](/miniprogram/dev/wxcloudservice/wxcloud/reference-sdk-api/utils/Cloud.CDN) 方法标记字段内容
1. 若 `Buffer` 非常小 (如  {
  return event.x + event.y
}
```

在小程序端发起对云函数 `add` 的调用：

```js
wx.cloud.callFunction({
  // 要调用的云函数名称
  name: 'add',
  // 传递给云函数的event参数
  data: {
    x: 1,
    y: 2,
  }
}).then(res => {
  // output: res.result === 3
}).catch(err => {
  // handle error
})
```

在云函数端任意云函数发起对云函数 `add` 的调用（完整云函数代码示例）：

```js
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

exports.main = async (event, context) => {
  const res = await cloud.callFunction({
    // 要调用的云函数名称
    name: 'add',
    // 传递给云函数的参数
    data: {
      x: 1,
      y: 2,
    }
  })
  // 3
  return res.result
}
```

小程序端 callback 风格调用：

小程序端同时支持 Callback 风格调用，如上 Promise 风格的调用可以用 Callback 风格改写：

```js
wx.cloud.callFunction({
  // 要调用的云函数名称
  name: 'add',
  // 传递给云函数的参数
  data: {
    x: 1,
    y: 2,
  },
  success: res => {
    // output: res.result === 3
  },
  fail: err => {
    // handle error
  },
  complete: () => {
    // ...
  }
})
```
