invoke

更新时间:
复制 MD 格式

This topic describes how to call a cloud function using the invoke method.

Method definition

mpserverless.function.invoke(functionName: string, functionArgs?: object): Promise<Result>

Request parameters

Field

Type

Required

Description

functionName

String

Yes

The name of the cloud function to call.

functionArgs

Object

No

The input parameters for the cloud function. The function accepts these parameters through ctx.args.

Return parameters

Field name

Type

Description

success

Boolean

The execution status.

requestId

String

The request ID.

result

Any

The content returned by the API. The content is determined by the developer's code and the content-type in the request header. The default value is application/json.

Examples

Suppose you have a cloud function named sum. The function is defined as follows.

'use strict';

module.exports = async (ctx) => {
  const {a, b} = ctx.args;
  return a + b;
}

The following example shows how to call the sum cloud function from a Mini Program.

const { result } = await mpserverless.function.invoke(
    'sum', 
    { a: 1, b: 1 }
);
console.log('1 + 1 = ', result);  // 1 + 1 = 2 

The following example shows how to call the sum cloud function from another cloud function.

'use strict';

module.exports = async (ctx) => {
    const { result } = await ctx.mpserverless.function.invoke(
        'sum', 
        { a: 1, b: 1 }
    );
    return result;
}