javascript - 解析作为参数传递的 JS 承诺
问题描述
在我的 JS 应用程序中,我需要在某个事件中下载多个(数百个)图像。一旦事件发生,所有图像都将在队列中被双关并下载。由于 Chrome 和其他浏览器只允许有限数量的并发下载,因此只能同时下载 5 个左右。其余的都排在队列中。
我的问题是,在下载图像时,用户可能会引发一个需要更高优先级下载的事件。但它被放在队列的末尾并等到较低优先级的东西被下载。
我决定实现我自己的队列,在那里我可以控制我的下载优先级。目前,当引发下载低公关图像的事件时,会在下载图像fetch
时立即创建和解决数百个承诺。
我不想返回一个获取承诺(将立即执行),而是返回一个可以在以后解决的承诺。然后将此承诺传递给我的排队函数,让它决定何时解决它。
这是发起呼叫的方式:
static addCall(params) {
let returnPromise = new Promise((resolve, reject) => { });
let CallParams = {
Promise: returnPromise,
}
//push call in a queue
Backend.CallQueue.push(CallParams);
//run queue
Backend.enforceQueue();
return returnPromise;
}
这是我的队列处理:
static ConcurrentCallsLimit = 3;
static CallQueue = [];
static RunningCalls = [];
static enforceQueue() {
//If currently running less concurrent calls then a maximum allowed - add more
if (Backend.RunningCalls.length < Backend.ConcurrentCallsLimit) {
for (let i = 0; i < Backend.ConcurrentCallsLimit - Backend.RunningCalls.length; i++) {
let nextCall = Backend.CallQueue.shift();
if (nextCall) {
//push in line & run
Backend.RunningCalls.push(nextCall);
Backend.runCall(nextCall);
}
}
}
}
还有一个 RunCall 方法:(试图解决作为参数传递的承诺)
static runCall(CallParams){
fetch("path", {...})
.then((resp)=>{
CallParams.Promise.resolve(resp); //this will not work :(
});
}
//CallParams.Promise.resolve is not a function
解决方案
推荐阅读
- d3.js - 如何更改 C3JS 垂直工具提示线颜色并隐藏 y 轴线
- reactjs - 将动态随机颜色推入深层嵌套图表状态?
- multidimensional-array - Lua 5.3.5 意外的 table.insert 行为
- qt - 不使用 GridView 或 ListView 而是使用 c++ 模型的结构化布局的 QML 解决方案
- php - 从头开始创建模块应用程序
- javascript - 这个 CSS 语法的名称?
- javascript - 在 Node.js 中的获取/创建操作中未找到错误
- twilio - Twilio JS 客户端立即挂断
- c# - 使用反射映射复杂对象
- php - 数据表,在数据集中添加另一列但不在表中显示