跳到主要内容

云函数

callFunction

1. 接口描述

接口功能:执行云函数

接口声明:callFunction<ParaT, ResultT>(callFunctionOptions: ICallFunctionOptions<ParaT>, opts?: ICustomReqOpts): Promise<CallFunctionResult<ResultT>>

2. 输入参数

字段类型必填说明
callFunctionOptionsICallFunctionOptions<ParaT>云函数调用请求参数
optsICustomReqOpts自定义配置,目前支持 SDK 请求超时时间设置,{timeout: number}

ICallFunctionOptions<ParaT>

云函数参数:

字段类型必填说明
namestring云函数名称
dataParaT云函数参数
qualifierstring云函数版本标识:$LATEST(最新版本) 1 2 3,缺省时按平台配置流量比例分配流量

云函数2.0 额外可以传参数,传入 type:'cloudrun' 参数后,将调用云函数2.0服务

字段类型必填说明
typecloudrun是否调用 基于 云托管的云函数2.0
methodstringHTTP 请求方法
pathstringHTTP 请求路径
headerRecord<string, string>HTTP 请求头
dataobjectHTTP 请求体

3. 返回结果

Promise<CallFunctionResult<ResultT>>

字段类型必填说明
resultResultT云函数执行结果
requestIdstring请求序列号,用于错误排查

函数执行报错,将通过异常抛出

4. 示例代码

import tcb from '@cloudbase/node-sdk'
const app = tcb.init({
env: 'xxx'
})

exports.main = async (event, context) => {
const res = await app.callFunction({
name: 'test',
data: { a: 1 }
})
console.log(res) // 打印函数调用结果

const res1 = await app.callFunction(
{
name: 'test',
data: { a: 1 }
},
{
timeout: 5000
}
)
console.log(res1)
}

云函数2.0 示例代码:

import tcb from '@cloudbase/node-sdk'

exports.main = async (event, context) => {
const { httpContext } = context
const { url, httpMethod } = httpContext
return `[${httpMethod}][${url}] Hello world!`

const tcbapp = tcb.init({ context })
const result = await tcbapp.callFunction({
name: 'helloworld',

// 云函数2.0 参数
type: 'cloudrun',
method: 'POST',
path: '/abc',
data: {
key1: 'test value 1',
key2: 'test value 2'
},
{
timeout: 5000
}
})
console.log(result)
}