代码之家  ›  专栏  ›  技术社区  ›  Woppi

如何在承诺中正确实现MongoDB异步/等待?

  •  2
  • Woppi  · 技术社区  · 8 年前

    我已经读到在 Promise 是异步/等待的反模式。下面的代码可以工作,但是我很好奇如何在没有 async 在里面 承诺 .

    如果我删除它,linter会告诉我如何在MongoDB查询中使用await。如果删除mongodb查询中的wait,那么它不会等待结果。

    export const getEmployees = (companyId) => {
      return new Promise(async (resolve, reject) => {
        const employees = await Employees.find(
          { companyId },
        );
    
        // other logic here...
    
        resolve({
          employees,
        });
      });
    

    谢谢。

    2 回复  |  直到 8 年前
        1
  •  4
  •   CertainPerformance    8 年前

    async Promise return getEmployees 功能:

    export const getEmployees = async (companyId) => {
      const employees = await Employees.find(
        { companyId },
      );
    
      // other logic here...
    
      return { employees };
    };
    

    catch 在消费者的 以防万一)

        2
  •  2
  •   Moshe Binieli    8 年前

    @CertainPerformance 回答说,这是使用async/await从MongoDB检索数据的完美方法,为了系统的正确性,我想增加一些关于如何处理错误的更多信息,以及更好的错误处理,以便向客户机返回关于他的请求的更好状态。

    try {
        const employees = await Employees.find({
            companyId
        });
        // You can add more logic here before return the data.
        return {
            employees
        };
    } catch (error) {
        console.error(error);
    }
    

    现在,让我们检查一下处理可能发生的错误的方法。

    export const getEmployees = async (companyId) => {
        try {
            const employees = await Employees.find({
                companyId
            });
            // You can add more logic here before return the data.
            return {
                employees
            };
        } catch (error) {
            console.error(error);
        }
    };
    

    将默认值赋给catch块中的变量:

    export const getEmployees = async (companyId) => {
        let employees;
    
        try {
            employees = await Employees.find({
                companyId
            });
            // You can add more logic here before return the data.
            employees = employees;
        } catch (error) {
            console.error(error);
        }
    
        if (employees) { // We received the data successfully.
            console.log(employees)
            // Business logic goes here.
        }
    
        return employees;
    };
    

    export const getEmployees = async (companyId) => {
        try {
            const employees = await Employees.find({
                companyId
            });
            // You can add more logic here before return the data.
            return {
                employees
            };
        } catch (error) {
            if (error instanceof ConnectionError) {
                console.error(error);
            } else {
                throw error;
            }
        }
    };
    

    关于异步等待的更多解释和您可以在这些答案中找到的更有用的方法。 How run async / await in parallel in Javascript

    推荐文章