重构typescript云函数使用promise chaining

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了重构typescript云函数使用promise chaining相关的知识,希望对你有一定的参考价值。

我是一个android开发人员,几乎没有网络经验。我写了一个云功能来注册用户。但太嵌套了。我知道我可以使用promise chaining或async / await。当我试图使用异步vs代码给出错误,它cannot find name, async,目标是ES6。当我尝试链接承诺时,它会发出像not all code paths returns a value这样的警告。这是我的代码

exports.register = functions.https.onRequest((request, response) => {
    const db = admin.firestore();
    const user: string = request.body['username'];
    const phone: number = request.body['phone'];
    const password: string = request.body['password'];

    return db.collection('rejectedContacts').where('contact', '==', phone).get()
        .then(rejectedContactsSnapShot => {
            if (rejectedContactsSnapShot.size > 0) {
                return response.json(
                    {
                        status: 0,
                        message: `Contact, ${phone} is blocked, please try again with another number`,
                        result: null
                    }
                );
            } else {
                return db.collection('users').where('contacts.phone', '==', phone).get()
                    .then(contactsSnapShot => {
                        if (contactsSnapShot.size > 0) {
                            return response.json(
                                {
                                    status: 0,
                                    message: `Contact, ${phone} is already assigned with an account. Did you forgot your pasword?`,
                                    result: null
                                }
                            );
                        } else {
                            return db.collection('users').add(
                                {
                                    user: user,
                                    password: password,
                                    isBlocked: false,
                                    joiningDate: Date.now(),
                                    phoneVerified: false,
                                    deleted: false,
                                    contacts:
                                        {
                                            phone: phone
                                        }

                                }
                            ).then((writeResult) => {
                                return response.json(
                                    {
                                        result: `User with ID: ${writeResult.id} added.`
                                    }
                                );
                            });
                        }
                    });
            }
        });
});

这是我改变承诺链时所尝试的,但是显示警告not all code paths return a value

exports.register = functions.https.onRequest((request, response) => {
    const db = admin.firestore();

    const user: string = request.body['username'];
    const phone: number = request.body['phone'];
    const password: string = request.body['password'];

    return db.collection('rejectedContacts').where('contact', '==', phone).get()
        .then(rejectedContactsSnapShot => {
            if (rejectedContactsSnapShot.size > 0) {
                return response.json(
                    {
                        status: 0,
                        message: `Contact, ${phone} is blocked, please try again with another number`,
                        result: null
                    }
                );
            } 
        }).then(notRejected=>{
            return db.collection('users').where('contacts.phone', '==', phone).get()
                    .then(contactsSnapShot => {
                        if (contactsSnapShot.size > 0) {
                            return response.json(
                                {
                                    status: 0,
                                    message: `Contact, ${phone} is already assigned with an account. Did you forgot your pasword?`,
                                    result: null
                                }
                            );
                        } 
                    });
        }).then(numberDoesNotExists=>{
            return db.collection('users').add(
                {
                    user: user,
                    password: password,
                    isBlocked: false,
                    joiningDate: Date.now(),
                    phoneVerified: false,
                    deleted: false,
                    contacts:
                        {
                            phone: phone
                        }

                }
            );
        }).then((writeResult) => {
            return response.json(
                {
                    result: `User with ID: ${writeResult.id} added.`
                }
            );
        });
});

任何人都可以帮我重新考虑这个代码使用async / await of promise chaining,这样它就更具可读性。

答案

在不知道你尝试了什么的情况下,我不确定你为什么会在第一时间得到错误,但是使用async / await进行简单的代码转换将是:

functions.https.onRequest(async (request, response) => {
    const db = admin.firestore();
    const user: string = request.body['username'];
    const phone: number = request.body['phone'];
    const password: string = request.body['password'];

    let rejectedContactsSnapShot = await db.collection('rejectedContacts').where('contact', '==', phone).get();
    if (rejectedContactsSnapShot.size > 0) {
        return response.json(
            {
                status: 0,
                message: `Contact, ${phone} is blocked, please try again with another number`,
                result: null
            }
        );
    } else {
        let contactsSnapShot = await db.collection('users').where('contacts.phone', '==', phone).get();
        if (contactsSnapShot.size > 0) {
            return response.json(
                {
                    status: 0,
                    message: `Contact, ${phone} is already assigned with an account. Did you forgot your pasword?`,
                    result: null
                }
            );
        } else {
            let writeResult = await db.collection('users').add({
                user: user,
                password: password,
                isBlocked: false,
                joiningDate: Date.now(),
                phoneVerified: false,
                deleted: false,
                contacts:{
                    phone: phone
                }
            })

            return response.json(
                {
                    result: `User with ID: ${writeResult.id} added.`
                }
            );
        }
    }
});

注意你的代码是一个非常大的chuck,没有更多的上下文,上面的代码可能包含错误,但这应该让你开始。

以上是关于重构typescript云函数使用promise chaining的主要内容,如果未能解决你的问题,请参考以下文章

在 TypeScript 中使用 Promises 的异步函数的正确错误模式

Typescript:Promise 的子类/扩展:不引用 Promise 兼容的构造函数值

typescript async函数必需返回promise么

Typescript 函数可以将 Promise<any> 作为 Promise<Bar> 返回吗?

当我从等待移动到 Promise.all 时,TypeScript 函数返回类型错误

使用 angularJS 和 Typescript 的 Promise