调用Google Cloud onCall函数时得到未定义的响应

时间:2019-11-22 06:11:20

标签: firebase firebase-authentication google-cloud-functions

我写了2个类似的函数,一个是onRequest,另一个是onCall(如documentation中所述)

functions / index.js

const products = [];
const LIMIT = 100;
for (let i = 0; i < LIMIT; i++) {
    products.push({
        name: "product" + i,
        price: "price" + i,
    });
}

exports.products1 = functions.https.onCall((input, context) => {
    const { page = 1, limit = 10 } = input;

    const startAt = (page - 1) * limit;
    const endAt = startAt + limit;

    return products.slice(startAt, endAt);
});

exports.products2 = functions.https.onRequest((request, response) => {
    const { page = 1, limit = 10 } = request.query;

    const startAt = (page - 1) * limit;
    const endAt = startAt + limit;

    return response.json(products.slice(startAt, endAt));
});

我可以使用curl从命令行调用onRequest http函数,但是当我尝试从应用程序代码调用onCall函数时(我在react-native上进行构建并使用Firebase移动电话号码身份验证),在响应。

App.js

async fetchProducts() {
        const instance = firebase.functions().httpsCallable('products1');
        try {
            const response = await instance({
                page: 1,
                limit: 15,
            })
                .then(res => console.warn('Res',res))
                .catch(err => console.warn('Error', err));
            console.warn('Response', response);
        } catch (httpsError) {
            console.log('Message', httpsError.message);

            // Check code
            if (httpsError.code === firebase.functions.HttpsErrorCode.NOT_FOUND) {
                console.error('Functions endpoint "order" not found');
            }
        }
    };

有人可以告诉我我在做什么错吗?

1 个答案:

答案 0 :(得分:1)

这是因为您同时使用async/awaitthen()方法。

如果您按以下方式修改代码,它将起作用:

async fetchProducts() {
        const instance = firebase.functions().httpsCallable('products1');
        try {
            const response = await instance({
                page: 1,
                limit: 15,
            })
            console.warn('Response', response);
        } catch (httpsError) {
            console.log('Message', httpsError.message);

            // Check code
            if (httpsError.code === firebase.functions.HttpsErrorCode.NOT_FOUND) {
                console.error('Functions endpoint "order" not found');
            }
        }
    };

您将在MDN doc中读到,您根本不需要使用then()

  

await表达式会暂停异步功能的执行   (即httpsCallable('products1'))并等待传递的Promise的   解决方案,然后恢复async函数的执行并   评估为解析值。