gpt4 book ai didi

javascript - 等待 Node.js Express 应用在 for 循环中调用 http.request

转载 作者:行者123 更新时间:2023-11-29 21:36:41 27 4
gpt4 key购买 nike

我的头快要爆炸了。请知道我等了大约一个星期才发布这个。无法弄清楚这一点的耻辱加上浪费的大量个人时间让我处于一个非常黑暗的地方。我问你 interwebs...请给我指路。

我正在编写我的第一个 NodeJS Express 4 应用程序,它将管理我的家庭自动化系统(它有一个 Rest API)。让我丧命的是我已经完成了 99% 的代码,我只是无法让它等待循环 http.request 完成,然后再从下面的函数中调用我的返回回调。

我已经尝试过,DeAsync、Async、wait.for,...我似乎无法得到它,主要是因为处于 for 循环中。谁能帮我解决这个问题。我只是无法很好地理解异步或回调来确定这一点。

最主要的是它接受一个带有名称:值对的对象,然后循环它们,调用一个网络服务,填充一个我正在调用的对象:ISYGetData,然后最后应该触发主回调,然后触发另一个函数来使用响应中的数据呈现网页模板。

如有任何帮助,我们将不胜感激。

function runISYGet(runISYGetInput, resInput, runISYGetCallback) {
//console.dir(runISYGetInput);
//console.log('length:' + runISYGetInput.length);
ISYGetData = [];

for (var i = 0; i < runISYGetInput.length; i++) {
// runISYGetInput Object Example:
// runISYGetInput = [
// { id: "36981", operation: "on" }
// , { id: "82563", operation: "on" }
// , { id: "52839", operation: "on" }
// , { id: "17383", operation: "on" }
// , { id: "38863", operation: "on" }

console.log('Starting Loop: ISYGet with %s,%s', runISYGetInput[i].id, runISYGetInput[i].operation);

if (runISYGetInput[i].operation.toUpperCase() == "ON") {
var operationTranslated = "DON"
} else {
var operationTranslated = "DOF"
}

if (typeof runISYGetInput[i].intensity === 'undefined') {
console.log('Nothing in intensity');
};

var options = {
hostname: hostname
,port: port
,path: "/rest/nodes/" + runISYGetInput[i].id + "/cmd/" + operationTranslated + "/"
,method: 'GET'
,auth: username + ':' + password
}

var req = https.request(options, function (res) {
console.log("Inside httpGet | Calling ISY Now");
//console.log("statusCode: ", res.statusCode);
//console.log("headers: ", res.headers);

res.on('data', function (chunk) {
console.log('BODY: ' + chunk);

if (i == 0) {
ISYGetData = [{
hostname: options.hostname
,port: options.port
,path: options.path
,statusCode: res.statusCode
,responseHeaders: JSON.stringify(res.headers)
,body: chunk.toString('utf8')
}]
} else {
ISYGetData = ISYGetData.concat([{
hostname: options.hostname
,port: options.port
,path: options.path
,statusCode: res.statusCode
,responseHeaders: JSON.stringify(res.headers)
,body: chunk.toString('utf8')
}])
};
});

req.on('error', function (e) {
console.error(e);
});

});
req.end();
}

console.log('This should happen last but doesnt currently, want to run runISYGetCallback(ISYGetData, resInput) after http gets are done and ISYGetData is populated');
// This callback renders the page with all needed data from the ISYGetData object
runISYGetCallback(ISYGetData, resInput);

最佳答案

这是一个为每个 https.request() 操作创建 promise 的方法,然后使用 Promise.all() 等待所有这些 promise 完成,让 promise 基础架构自动将所有数据收集到一个数组中,该数组的顺序与请求的顺序相同。

function runISYGet(runISYGetInput, resInput, runISYGetCallback) {
var operationTranslated, promises = [], options;
for (var i = 0; i < runISYGetInput.length; i++) {
if (runISYGetInput[i].operation.toUpperCase() == "ON") {
operationTranslated = "DON";
} else {
operationTranslated = "DOF";
}
if (typeof runISYGetInput[i].intensity === 'undefined') {
console.log('Nothing in intensity');
}
// create new options object for each cycle through the loop
options = {
hostname: hostname,
port: port,
path: "/rest/nodes/" + runISYGetInput[i].id + "/cmd/" + operationTranslated + "/",
method: 'GET',
auth: username + ':' + password
};

promises.push(new Promise(function(resolve, reject) {
// save options locally because it will be reassigned to a different object
// before it gets used in the callback below
var localOptions = options;
var req = https.request(localOptions, function (res) {
var data = "";
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function() {
// resolve with the accumulated data
// do it this way so that the promise infrastructure will order it for us
resolve({
hostname: localOptions.hostname,
port: localOptions.port,
path: localOptions.path,
statusCode: res.statusCode,
responseHeaders: JSON.stringify(res.headers),
body: data.toString('utf8')
});
});
});
req.on('error', function (e) {
console.error(e);
reject(e);
});
req.end();
}));
}
// now wait for all promises to be done
Promise.all(promises).then(function(allData) {
// This callback renders the page with all needed data
// when all the https.request() calls are done
runISYGetCallback(allData, resInput);
}, function(err) {
// figure out what to do here when there was an error in one or more of the https.request() calls
});
}

注意:如果您使用为您 promise 请求模块的请求 promise 模块,您可以进一步简化这个过程,但我选择展示一个不依赖任何新模块的实现

部分更改列表:

  1. 为循环中的每个请求创建一个新的 promise
  2. 使用 Promise.all() 等待所有 promise 完成
  3. 为每次通过循环分别捕获选项对象,因此我们正在使用的选项对象不会在异步处理期间被下一个循环覆盖
  4. 让 promises 捕获所有结果,这样它们就会按正确的顺序排列它们(而不是在它们到达时将它们串联起来)
  5. 将每个请求到达的所有数据 block 收集成一个片段(因为数据可以到达多个 block )
  6. 根据您未使用的 res.on('end') 触发 promise 的完成
  7. req.on('error') 移到它所属的更高级别
  8. 在请求错误时使用 promise rejection 将错误传播回最高级别
  9. 将局部变量的声明移到 for 循环之外。

仅供引用,您可能还想通过从 runISYGet 函数返回 promise 来替换 runISYGetCallback,如下所示:

function runISYGet(runISYGetInput, runISYGetCallback) {
var operationTranslated, promises = [], options;
for (var i = 0; i < runISYGetInput.length; i++) {
if (runISYGetInput[i].operation.toUpperCase() == "ON") {
operationTranslated = "DON";
} else {
operationTranslated = "DOF";
}
if (typeof runISYGetInput[i].intensity === 'undefined') {
console.log('Nothing in intensity');
}
// create new options object for each cycle through the loop
options = {
hostname: hostname,
port: port,
path: "/rest/nodes/" + runISYGetInput[i].id + "/cmd/" + operationTranslated + "/",
method: 'GET',
auth: username + ':' + password
};

promises.push(new Promise(function(resolve, reject) {
// save options locally because it will be reassigned to a different object
// before it gets used in the callback below
var localOptions = options;
var req = https.request(localOptions, function (res) {
var data = "";
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function() {
// resolve with the accumulated data
// do it this way so that the promise infrastructure will order it for us
resolve({
hostname: localOptions.hostname,
port: localOptions.port,
path: localOptions.path,
statusCode: res.statusCode,
responseHeaders: JSON.stringify(res.headers),
body: data.toString('utf8')
});
});
});
req.on('error', function (e) {
console.error(e);
reject(e);
});
req.end();
}));
}
// return master promise that is resolved when all the other promises are done
return Promise.all(promises);
}

// usage
runISYGet(...).then(function(allData) {
// process the data here
}, function(err) {
// handle error here
});

关于javascript - 等待 Node.js Express 应用在 for 循环中调用 http.request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34665674/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com