【问题标题】:use async await to build api使用 async await 构建 api
【发布时间】:2020-06-22 05:59:19
【问题描述】:

我已经用 express 编写了一个 Node api。在这个 api 中,我从数据库处理中获取一些数据,并将最终数据作为 api 有效负载发送。

这是我的代码..

exports.getAllAco =  (req, res) => {
    let acoList = [], i = 0;

    let condaions = {
        deleted: 0,
    }

    let attributes = ['id', 'name', 'email', 'type', 'phone', 'gender', 'main_sys_id', 'avatar', 'in_service', 'created_by']
    Methods.getAllData(User, condaions, attributes).then((userList) => {
            userList.map( user => {
                i = i + 1;
                if (user.dataValues.type == 'aco') {
                    let condations = {
                        aquisition_member_id: user.dataValues.id,
                        deleted: 0
                    }

                    Methods.getDetailsFromTwoAssociateTable(condations, Task, DetailTask).then(tasks => {
                        let x = {
                            user: user,
                            tasks: tasks
                        }

                        x.user.dataValues.totalTask = tasks.length;

                        let index = 0;

                        x.user.dataValues.userTotalAssigned = 0, x.user.dataValues.userTotalCalled = 0, x.user.dataValues.userTotalConverted = 0, x.user.dataValues.userTotalRejected = 0;

                        tasks.map(v=>{
                            x.tasks[index].dataValues.totalAssignedCustomer = v.dataValues.detail_tasks.length;
                            x.tasks[index].dataValues.totalCalled = 0;
                            x.tasks[index].dataValues.totalConverted = 0;
                            x.tasks[index].dataValues.totalRejected = 0;
                            v.dataValues.detail_tasks.map(detail_task=>{

                                 x.user.dataValues.userTotalAssigned += 1;

                                if(detail_task.dataValues.phone_call_status == 'called' ){
                                    x.tasks[index].dataValues.totalCalled += 1;
                                    x.user.dataValues.userTotalCalled +=1;
                                }

                                else if(detail_task.dataValues.phone_call_status == 'confirmed'){
                                    x.tasks[index].dataValues.totalConverted +=1;
                                    x.user.dataValues.userTotalConverted += 1;
                                }

                                else{
                                    x.user.dataValues.userTotalRejected += 1;
                                    x.tasks[index].dataValues.totalRejected += 1;
                                }
                            })
                            index=index+1;
                        })

                        // x.user.dataValues.totalAssigned = totalAssigned;

                        acoList.push(x)                           
                    })
                }
            })
            return acoList;
    }).then(acoList=>{
       setTimeout(() => {
        Methods.successResponse(req, res, acoList)
       }, 2000);
    }).catch((error) => {
        ErrorResMethods.errorResponse(req, res, error);
    })
}

要发送实际结果,我必须等待两秒钟,否则响应为空。

如何使用 async/await 来实现它。

【问题讨论】:

    标签: node.js express async-await


    【解决方案1】:

    我想这样的事情应该可以完成。

    exports.getAllAco = async (req, res) => {
      let i = 0;
    
      const condaions = {
        "deleted": 0
      };
    
      const attributes = ["id", "name", "email", "type", "phone", "gender", "main_sys_id", "avatar", "in_service", "created_by"];
      const userList = await Methods.getAllData(User, condaions, attributes);
      const acoList = await Promise.all(userList.map(async user => {
        i += 1;
        if (user.dataValues.type == "aco") {
          const condations = {
            "aquisition_member_id": user.dataValues.id,
            "deleted": 0
          };
    
          const tasks = await Methods.getDetailsFromTwoAssociateTable(condations, Task, DetailTask);
          const x = {
            "user": user,
            "tasks": tasks
          };
    
          x.user.dataValues.totalTask = tasks.length;
    
          let index = 0;
    
          x.user.dataValues.userTotalAssigned = 0, x.user.dataValues.userTotalCalled = 0, x.user.dataValues.userTotalConverted = 0, x.user.dataValues.userTotalRejected = 0;
    
          tasks.forEach(v => {
            x.tasks[index].dataValues.totalAssignedCustomer = v.dataValues.detail_tasks.length;
            x.tasks[index].dataValues.totalCalled = 0;
            x.tasks[index].dataValues.totalConverted = 0;
            x.tasks[index].dataValues.totalRejected = 0;
            v.dataValues.detail_tasks.map(detail_task => {
    
              x.user.dataValues.userTotalAssigned += 1;
    
              if (detail_task.dataValues.phone_call_status == "called") {
                x.tasks[index].dataValues.totalCalled += 1;
                x.user.dataValues.userTotalCalled += 1;
              } else if (detail_task.dataValues.phone_call_status == "confirmed") {
                x.tasks[index].dataValues.totalConverted += 1;
                x.user.dataValues.userTotalConverted += 1;
              } else {
                x.user.dataValues.userTotalRejected += 1;
                x.tasks[index].dataValues.totalRejected += 1;
              }
            });
            index += 1;
          });
          return x;
        }
      })
      Methods.successResponse(req, res, acoList);
    
    

    【讨论】:

    • 为什么setTimeout函数还在?
    • 我不知道这样做的意图。如果你不需要它,你可以删除它。因为您的呼叫现在正确异步。早些时候它不是;t
    • 为了捕捉错误,您可以将整个代码包装在try..catch
    • 有一些错误,请检查您的答案吗?
    • 我的回答是让您了解如何做到这一点。如果您遇到错误,请在此处提及或尝试找出可能的原因
    猜你喜欢
    • 2021-11-18
    • 2019-02-04
    • 1970-01-01
    • 2019-09-30
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 2018-07-05
    • 1970-01-01
    相关资源
    最近更新 更多