gpt4 book ai didi

javascript - Node.js 中的请求优先级队列

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:48:07 24 4
gpt4 key购买 nike

我有一个脚本可以使用 Node.js 中的 RESTful API 将产品添加到远程数据库。它运行良好,但我想更改处理 HTTP 请求的优先级。这里有一些代码可以更好地说明我正在尝试做的事情:

step(
function initializeCategories() {
createCategories(products, this);
},
function createProducts(err, categoriesHash) {
console.log("\nCreating products:");
console.log("==================");

var group = this.group(),
productDoneCallback;

products.forEach(function (product) {
product.categories = categoriesHash[product.category + "/" + product.make + "/" + product.model];
productDoneCallback = group();

step(
function createProduct() {
postProduct(convertToBigCommerceObj(product), this);
},
function overwriteProduct(err, product, allowOverwrite) {
if (err) {
console.log(err);
}

allowOverwrite = allowOverwrite || false;

if (allowOverwrite) {
updateProduct(product, this);
} else {
this(err, product);
}
},
function addExtraInfo(err, product) {
addImage(product, productDoneCallback);
}
);
});
},
function printStats(err) {
if (err) {
logError(err);
}

var endTime = +new Date(),
duration = endTime - startTime;

console.log("\nFinished after " + (duration / 1000 / 60) + " minutes");
console.log(productsAdded + " Products added successfully");
console.log(productsUpdated + " Products updated successfully");
console.log(productsSkipped + " Products skipped");
console.log("Average time (milliseconds) per product was : " + (duration / totalNumProducts ));
console.log("For more information see error log (error.log)" );
}
);

在此代码中,产品图片总是在添加完所有产品后最后添加。这是因为 forEach 循环立即将所有 postProduct 请求放入 Node 事件队列。在第一个产品发布到服务器后,另一个条目被添加到队列的末尾以添加该产品的图像。相反,我希望新条目浮到队列顶部并成为下一个要处理的条目(不是另一个产品帖子,可以等待)。

我意识到要做到这一点,我需要一个优先级队列。我只是不确定如何在 Node 和 Javascript 中实现这一点。

更新:在 https://github.com/STRd6/PriorityQueue.js 找到 PriorityQueue 的实现之后,真正的麻烦是每次请求完成时异步处理队列。或者更像是每次有可用的 http channel 被释放时,我们需要采用最高优先级的项目。

最佳答案

每当您听到“优先队列”时,您应该会想到堆数据结构。它们不是唯一的方法,但它们实现起来很简单,因此是一个很好的第一步。

参见 http://eloquentjavascript.net/appendix2.html用于随机实现。他们假设当您创建堆时,您会传入一个函数,该函数接受一个元素并返回其优先级。在您的情况下,您可以存储 [priority, object] 之类的元素,并使用 function (x) {return x[0]} 之类的函数初始化堆。

关于javascript - Node.js 中的请求优先级队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11092633/

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