You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js调用Odoo XML-RPC API检查用户存在时返回undefined的问题求助

问题原因与解决方案

你的判断完全正确:函数返回undefined是因为所有return都写在嵌套的回调函数里,这些返回只对当前回调生效,和外层的user_exist函数无关。而且原函数里的异步操作(connect、execute_kw)还没执行完,外层函数就已经执行结束,自然返回undefined。

要解决这个问题,核心是把回调式的异步操作转换成Promise,再通过async/await让异步代码同步化执行,这样外层函数就能正确返回结果。

具体实现步骤

  1. 将Odoo的回调方法包装为Promise:把odoo.connect和odoo.execute_kw转换成返回Promise的函数,这样就能用await等待异步操作完成。
  2. 重写user_exist为async函数:在函数内部用await依次执行连接、查询操作,最后返回判断结果。
  3. 优化查询逻辑:用search_read替代先search再read的两步操作,减少一次数据库请求,提升效率。

修改后的代码

// 包装connect为Promise
function odooConnect() {
  return new Promise((resolve, reject) => {
    odoo.connect((err) => {
      if (err) reject(err);
      else resolve();
    });
  });
}

// 包装execute_kw为Promise
function odooExecuteKw(model, method, params) {
  return new Promise((resolve, reject) => {
    odoo.execute_kw(model, method, params, (err, value) => {
      if (err) reject(err);
      else resolve(value);
    });
  });
}

async function user_exist(email) {
  try {
    // 等待连接成功
    await odooConnect();
    console.log('Connected to Odoo server.');

    // 用search_read一步完成搜索+读取,只获取login字段和active=true的用户
    const users = await odooExecuteKw(
      'res.users',
      'search_read',
      [[['active', '=', true]], ['login']]
    );

    // 检查email是否存在
    const exists = users.some(user => user.login === email);
    return exists ? "User exist" : "user doesn't exist";
  } catch (err) {
    console.error(err);
    // 出错时可以返回错误信息或自定义内容
    return "Error checking user existence";
  }
}

调用方式

因为user_exist是async函数,调用时需要用await或者.then()获取结果:

// 方式1:在async函数内调用
async function checkUser() {
  const result = await user_exist('test@example.com');
  console.log(result);
}
checkUser();

// 方式2:用then链式调用
user_exist('test@example.com').then(result => {
  console.log(result);
}).catch(err => {
  console.error(err);
});

关键说明

  • 包装Promise是为了让异步操作能被await处理,确保外层函数等待所有异步操作完成后再返回结果。
  • search_read是Odoo提供的合并方法,直接返回符合条件的记录字段,比分开调用search和read更高效。
  • 用Array.some()替代for循环,代码更简洁,逻辑更清晰。

内容的提问来源于stack exchange,提问作者Zine Labidine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 07:18:30