承诺队列?

时间:2016-06-18 16:06:03

标签: javascript http promise

我有一个应用程序正在发送一个http请求,每次用户输入时都会返回一个promise。我每隔500毫秒就进行一次。有时我要求的api需要很长时间才能回复。例如,我针对a+x提出了需要很长时间才能回复的搜索请求,然后用户继续输入以完成a+x的查询,该查询几乎立即解决但a的结果被前一个let bottomConstraint = NSLayoutConstraint(item: sideMenuView.view, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0) 的请求覆盖。

TL; DR:如果在当前解析之前调用新的promise,如何取消当前

2 个答案:

答案 0 :(得分:2)

创建一个计算您的请求的变量:

var effectiveRequestNumber = 0;

function asyncRequest() {       
    var requestNumber = ++effectiveRequestNumber; // storing our request number
    doSomething().then(function(response) {
        // if the function was invoked after this request, then these two won't match
        if (effectiveRequestNumber !== requestNumber) {
            return;
        } 
        applyResponse(response); // we are fine - applying the response
    });
}

答案 1 :(得分:1)

我通常处理重叠查询的方式,我只想要最后一个的结果是记住我可以在回调中检查的内容。

你还没有引用任何让它变得棘手的代码,但这里有一个例子:



"use strict";
// NOTE: Will only run if your browser supports promises.

// Scoping function to avoid globals
(function() {
  // We keep track of the most recent promise
  var lastSomethingRequest = null;
  
  // Our function that does something async
  function doSomething(value) {
    console.log("doing request for " + value);
    
    // Start the async, remember the promise
    var p = new Promise(function(resolve) {
      setTimeout(function() {
        resolve("resolve for " + value);
      }, Math.floor(Math.random() * 500));
    });
    
    // Remember that as the most recent one
    lastSomethingRequest = p;
    p.then(function(result) {
      // Use the result only if it's the most recent
      if (lastSomethingRequest === p) {
        console.log("Use this result: " + result);
        lastSomethingRequest = null; // Release the promise object
      } else {
        console.log("Disregard outdated result: " + result);
      }
    });
  }

  // Generate 5 requests in a row that will complete in varying
  // amounts of time, where we only want the result of the last one
  for (var n = 0; n < 5; ++n) {
    doSomething(n);
  }
})();
&#13;
&#13;
&#13;