2013-05-01 38 views
0

我正在使用Azure移动服务。我有两个表,我试图做的是从TableA中获取一个列值,当我在TableB上运行插入时,通过检查它与来自TableB的列值匹配的位置。Azure移动服务器脚本 - 从另一个表中获取列值

我的刀片服务器脚本如下:

function insert(item, user, request) { 

    var TableA_Table = tables.getTable('TableA'); 

    tableA_Table 
     .where({ columnValue: item.columnValue }) 
     .read ({ success: setItemColumnValue }); 

    request.execute(); 

    function setItemColumnValue(result) 
    { 
     item.tableA_id = result.id; 
    } 
} 

我已经证实了我的tableA_Table.where命令从TableA的拉动正确的行,但是当我内输入的console.log(结果) setItemColumnValue函数,它打印未定义。

我发现的所有文档都显示类似于我的代码,但我无法弄清楚我要出错的地方。 任何帮助赞赏!

回答

2

脚本中存在一些问题。首先,你必须记住的是表访问代码是异步的。发生了什么是该函数是回调函数'setItemColumnValue'只在request.execute();后被调用,这意味着该项目将被插入,而不会被tableA_id成员集。另一个问题是,read成功回调返回结果数组,而不是单个结果(就像SQL SELECT FROM语句),因此数组没有id字段 - 其成员拥有它。尝试像下面的代码一样重写代码,这应该工作。

function insert(item, user, request) { 

    var TableA_Table = tables.getTable('TableA'); 

    tableA_Table 
     .where({ columnValue: item.columnValue }) 
     .read ({ success: setItemColumnValue }); 

    function setItemColumnValue(results) 
    { 
     if (results.length === 0) { 
      // what should it do if there is no matching on table A? 
      // Assuming here that this is an error. 
      request.respond(statusCodes.BAD_REQUEST, { error: 'No matching item in table A' }); 
     } else if (results.length === 1) { 
      item.tableA_id = results[0].id; 
      request.execute(); 
     } else { 
      // what should it do if there are multiple matches on table A? 
      // Assuming here that this is an error. 
      request.respond(statusCodes.BAD_REQUEST, { error: 'Multiple matches in table A' }); 
     } 
    } 
} 
+0

谢谢卡洛斯!我已经更新了我提到的代码,现在我直接访问数组成员的id值,现在我明白了回调函数的异步特性。我唯一剩下的问题是Azure抛出'错误:执行不能被调用多次',即使我的第二个request.execute在我的setItemColumnValue函数中,就像你已经布局的一样。有任何想法吗? – Naz 2013-05-01 13:54:27

+0

对不起,我忘了在'read'调用之后删除对'request.execute()'的调用。由于在读回调时,所有的代码路径都会响应请求(通过调用'request.respond'或'request.execute'),原来的不再需要。我更新了答案中的代码。 – carlosfigueira 2013-05-01 14:26:31

+0

再次感谢Carlos,非常感谢。 – Naz 2013-05-02 03:00:59

相关问题