通过vue-resource限制并发HTTP调用

时间:2017-10-26 06:32:26

标签: javascript vue.js vuejs2 vue-resource

我们在应用程序中同时通过vue-resource执行多个 override func viewWillAppear(_ animated: Bool) { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Category") if let fetchedObjects = try? managedContext.fetch(fetchRequest), !fetchedObjects.isEmpty { let category = fetchedObjects.first as? NSManagedObject self.theProductId = category?.value(forKey: "productId") as! String print(theProductId) } 调用。有没有办法设置限制,以便vue-resource对请求进行排队并根据此限制执行调用?

1 个答案:

答案 0 :(得分:0)

我没有使用Vue资源。

我只是用另一个诺言来包裹诺言:

const callBackFunction = function (valueToReturn, promise) {
  pendingRequestsArr.pop();
  if (waitingRequestsArr.length > 0) {
    executeXHR(waitingRequestsArr.shift())
  }
  if (valueToReturn.body && !valueToReturn.body.hasOwnProperty('error')) {
    if (promise) promise(valueToReturn.body.content || valueToReturn.body);
    return valueToReturn.body.content || valueToReturn.body;
  }
  else
    return valueToReturn.error
};

function executeXHR(obj) {
    if (!AJAX_CONCURRENT || pendingRequestsArr.length < AJAX_CONCURRENT) {
      pendingRequestsArr.push(obj.resource(obj.data).then((response) => callBackFunction(response, obj.promise)))
    } else {
      waitingRequestsArr.push(obj);
    }
}
function wrapPromise(resource, data){
  return new Promise((resolve, reject)=>{
    executeXHR({"resource": resource, "data": data, "promise": resolve});
  })
}
getAllProjects() {
        return wrapPromise($projects.get);//$project.get == $http.get('/projects')
      },