在api respone中实现异步等待

时间:2020-03-05 07:44:49

标签: node.js express async-await

我正在使用Node JS开发API。下面是API的代码。

exports.getAllUser = async (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']
   await Methods.getAllData(User, condaions, attributes).then((userList) => {
        if (userList) {
            // Methods.successResponse(req, res, userList);
            console.log(userList.length, 'length of user')
            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(task => {
                        acoList.push(
                            {
                                user:user,
                                task: task
                            }
                        )
                    })
                }
                // if( i == userList.length-1 ){
                //     Methods.successResponse(req, res, acoList);
                // }
            })
        }
    }).catch((error) => {
        ErrorResMethods.errorResponse(req, res, error);
    })

   setTimeout(() => {
     Methods.successResponse(req, res, acoList)
   }, 5000);
}

在这里,我尝试实现异步来收集数据,并且在收集数据之后它将给出响应。

,但是无法使用Async。这就是为什么我使用setTimeOut()来实现的原因。

显然,这不是一个好习惯,但是在完成第一个任务后如何发送响应。

2 个答案:

答案 0 :(得分:1)

您可以通过以下方式使用代码:

// ... initialization of variables as per required
await Methods.getAllData(User, condaions, attributes).then((userList) => {

  if (userList) {
        console.log(userList.length, 'length of user')
        return Promise.each(userList, (list, key, length) => {    
            // prepare acoList here and return acoList
        }).then((acoList) => {
            return acoList
        })                
    } else {
        // handle else condition and return empty acoList
    }
}).then((acoList) => {
  Methods.successResponse(req, res, acoList)
}).catch((error) => {
  ErrorResMethods.errorResponse(req, res, error);
})

答案 1 :(得分:1)

您发布的代码有很多问题,您应该针对这样的事情。

exports.getAllUser = (req, res) => {
  let condations = {
    deleted: 0,
  }
  const attributes = ['id', 'name', 'email', 'type', 'phone', 'gender', 'main_sys_id', 'avatar', 'in_service', 'created_by']

  // you should return something if you are planning on using the function elsewhere
  // like const users = await getAllUsers()
  return Methods.getAllData(User, condations, attributes).then(async (userList) => {
    if (userList) {
      console.log(userList.length, 'length of user')
      const acoList = await userList.reduce(async (acc, user) => {
        if (user.dataValues.type === 'aco') {
          condations = {
            aquisition_member_id: user.dataValues.id,
            deleted: 0,
          }

          const task = await Methods.getDetailsFromTwoAssociateTable(condations, Task, DetailTask)
          acc.push({
            user: user,
            task: task,
          })
        }
        return acc
      }, [])
      Methods.successResponse(req, res, acoList)
      return acoList
    }
    return userList
  }).catch(error => {
    ErrorResMethods.errorResponse(req, res, error)
    return []
  })
}