javascript - Azure 表存储返回查询结果
问题描述
我正在尝试创建一个 Azure 函数,该函数将接受参数并返回存储在 Azure 表中的值。我相信我遇到的问题与 javascript 的关系比与 Azure Table SDK 的关系更大。
您应该如何通过 http 响应从查询中返回值?我附上了代码的副本,它应该解释我在哪里感到困惑。我的主要困惑是由于我可以调用context.log()
但无法context.res{}
从查询方法中的函数调用。
我知道作用域与它有关,但我不是 javascript 和嵌套函数方面的专家。一些指导或示例将不胜感激
var azure = require('azure-storage');
module.exports = function (context, req) {
context.log('Some Function');
var hostUri = 'https://*******.table.core.windows.net'
var sasToken = 'abc123'
if (req.query.value) {
var tableService = azure.createTableServiceWithSas(hostUri, sasToken)
var nothing = tableService.retrieveEntity('Table', 'Partition', 'Row', function(error, result, response) {
if (!error) {
context.log('I am able to send data to the logs here')
context.res = {
status: 200,
body: "This is what I am tring to return -> " + JSON.stringify(result)
};
}
})
context.res = {
status: 200,
body: "I'm able to get a response here"
};
}
else {
context.res = {
status: 400,
body: "Somthing went wrong..."
};
}
context.done();
};
解决方案
先解决办法:
if (req.query.value) {
var tableService = azure.createTableServiceWithSas(hostUri, sasToken)
tableService.retrieveEntity('Table', 'Partition', 'Row', function(error, result, response) {
if (!error) {
context.log('I am able to send data to the logs here')
context.res = {
status: 200,
body: "This is what I am tring to return -> " + JSON.stringify(result)
};
}
else{
context.res = {
status: 400,
body: error
};
}
context.done();
})
}
else {
context.res = {
status: 400,
body: "Value is empty"
};
context.done();
}
解释:
让我们将 context.res 依次标记为 c1 和 c2 以避免冗余。
你被回调函数抓住了。function(error, result, response){}
在从远程服务器检索到实体(或发生错误)之前,不会执行回调。这个操作可能需要一些时间,程序在等待它完成的同时继续执行,这个模式被称为asynchronous
。
因此,回调中的代码片段 c1 不会立即执行,而是 c2 会立即执行。然后context.done();
在检索到的实体之前运行(您会看到响应消息I'm able to get a response here
),因此永远不会调用回调。
依赖回调结果的代码应该包含在回调中,以便在回调完成后准确执行。放入context.done();
回调和其他部分以确保它不会提前运行。
还有一篇关于异步 JavaScript的博客供您参考。
推荐阅读
- android - MPAndroidChart:带间隙的水平条形图
- amazon-web-services - 如何使用客户端 golang 在 cloudwatch 中拉/推指标
- php - Symfony 如何/在哪里评论
我试图允许通过Symfony 5.0.8的
<?php
标签在论坛上使用标签。code
不知何故 Symfony(或 Twig,我不能在这里说)神奇地把它放在评论之间,我真的不知道在哪里、如何以及为什么这样做。
raw
显然,我正在通过过滤器在我的树枝模板中传输- augmented-reality - 如何使用 AR.js 在图像上渲染视频,使其保持完美的轨道和正确的大小?
- python - 当 python 脚本从 crontab 运行时,__name__ 会是什么?
- python - 如何在 tkinter 中将多个项目从一个列表框移动到另一个列表框?
- r - ggplot - geom_histogram - 边界在做什么
- c# - 如何在 C# 中为 Perceptron 训练多个输入?
- python - 机器学习和感知器
- css - 弹性物品不“伸展”