首页 > 解决方案 > 解析作为参数传递的 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

标签: javascriptpromisees6-promise

解决方案


推荐阅读