强制异步Node.js会导致 azure



我通常使用其他编程语言,需要实现一些node.js代码,但我完全不熟悉: 目前,我只希望 azure 函数应用的结果实际上依赖于我调用 api。我将HTTP调用放入承诺中,并正在等待结果:

module.exports = async function (context, req) {
context.res = {
body: {
"data": [{
"value": "start"
}]
}
};
await callapi(context);
};
function callapi(context){
var options = {
host: 'jsonplaceholder.typicode.com',
port: 443,
path: '/todos/1',
method: 'GET'
};
var p1 = new Promise(
function(resolve, reject) {
callback = function(httpres) {
var str = '';
response.on('error', function (err) {
context.res = {body: {"data": [{"value": "error"}]}};
});
httpres.on('data', function (chunk) {
str += chunk;
});
httpres.on('end', function () {          
resolve(str);
});
}
https.request(options, callback).end();
}
);
p1.then(function(reqhtml) {
context.res = {
body: {
"data": [{
"value": "it worked"
}]
}
};
})
}

我对此的期望是,它会 - 取决于是否可以访问服务器 - 要么返回(具有(值"它工作"或"错误"的上下文,但它不等待承诺,只是返回"开始"。

如何等待 Azure 中的异步函数?除此之外我没有代码;此函数仅通过另一个 API 调用,从那里我只能使用图形用户界面以受限制的方式操作结果。有没有办法强制node.js在这个函数中等待?

我已经清理了你的代码。

module.exports = async function (context, req) {
const value = await callapi();
context.res = {
body: {
data: [{
value
}]
}
};
};
// this function does not need any parameters, 
// it's sole job is to make a https request to a static endpoint 
// and return a value based on wether there was an error or not
function callapi(){
var options = {
host: 'jsonplaceholder.typicode.com',
port: 443,
path: '/todos/1',
method: 'GET'
};
return new Promise(function(resolve, reject) {
const req = https.request(options, res => {
let str = "";
res.on('data', function(chunk) {
str += chunk;
});
res.on('end', function() {
resolve(str);
});
});
res.on('error', reject);
req.end();
})
.then(() => "it worked")
.catch(() => "error");
}

目前,我只希望我的 azure 函数应用的结果实际上依赖于我调用 api。

由于您的callapi不返回任何内容,因此await callapi()await undefined,这将在下一个刻度中解决。(基本上,在所有当前同步代码执行完毕之后,在服务器可以将任何数据发送回给您之前很久(

2nd:变异对象是不受欢迎的,因为(精神上(很难跟踪所有可能受此变化影响的地方; 因此很危险。 最好返回包含更改的副本。

第三:保持简单callapi在需要了解context的地方不做任何事情

NPM 库 desync 解决了这个问题:

module.exports = async function (context, req) {    
var uri = <uri>;
var source = get_source_at(uri)
context.res = { body: { "data": [{"value": source}] } };
};
function get_source_at(uri){
var request = require("request");
var deasync = require("deasync");
var source;
request({ uri:uri, headers: <headers>}
, function (error, response, body) {
source = body;
});
while(source === undefined) { //wait until async HTTPS request has finished
deasync.runLoopOnce();
}
return source;
}

最新更新