问题描述:

I have a search function that is debounced. It is called each time a keyup event is fired on a text area.

The idea that results are fetched as the user types in the text area.

{

search: _.debounce(search, 200),

}

But, there is no guarantee AFAICT that the search calls to the backend will return in the order they were sent (network latency, server vagaries), meaning that the results could (although unlikely) correspond to an earlier search term.

So I want to cancel (or at least ignore the response to) any in-flight requests when a search is performed.

I have two questions:

  • Is this a real problem that needs solving? (I have not seen it solved before), and

  • Will the following code help me achieve this?

function ignoreStale(fn) {

var latest = 0;

return function() {

var id = ++latest; // increments latest too

return fn.apply(this, arguments)

.then(function(result) {

if (id !== latest) {

throw new Error('Stale callback.');

}

return result;

});

}

}

var callCount = 0;

var o = {

foo: ignoreStale(foo),

};

function foo(val) {

callCount--;

return new Promise(function(resolve, reject) {

setTimeout(resolve.bind(null, val), (5000 + callCount*200));

});

}

function go (val) {

o.foo(val).then(doSomething).catch(error);

}

go('1'); // returns third

go('12'); // returns second

go('123'); // returns first

function error(err) {

document.write(err, '<br/>');

}

function doSomething(val) {

document.write('Doing something:', val, '<br/>');

}

相关阅读:
Top