Skip to content

Commit 545e723

Browse files
committed
Update SCAN example code
1 parent f7f3e9a commit 545e723

File tree

1 file changed

+21
-8
lines changed

1 file changed

+21
-8
lines changed

examples/scan.js

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,20 +15,33 @@ function scan() {
1515

1616
// Update the cursor position for the next scan
1717
cursor = res[0];
18+
// get the SCAN result for this iteration
19+
var keys = res[1];
1820

19-
// From <http://redis.io/commands/scan>:
20-
// 'An iteration starts when the cursor is set to 0,
21-
// and terminates when the cursor returned by the server is 0.'
22-
if (cursor === '0') {
23-
return console.log('Iteration complete');
24-
}
2521
// Remember: more or less than COUNT or no keys may be returned
2622
// See http://redis.io/commands/scan#the-count-option
2723
// Also, SCAN may return the same key multiple times
2824
// See http://redis.io/commands/scan#scan-guarantees
25+
// Additionally, you should always have the code that uses the keys
26+
// before the code checking the cursor.
27+
if (keys.length > 0) {
28+
console.log('Array of matching keys', keys);
29+
}
2930

30-
if (res[1].length > 0) {
31-
console.log('Array of matching keys', res[1]);
31+
// It's important to note that the cursor and returned keys
32+
// vary independently. The scan is never complete until redis
33+
// returns a non-zero cursor. However, with MATCH and large
34+
// collections, most iterations will return an empty keys array.
35+
36+
// Still, a cursor of zero DOES NOT mean that there are no keys.
37+
// A zero cursor just means that the SCAN is complete, but there
38+
// might be one last batch of results to process.
39+
40+
// From <http://redis.io/commands/scan>:
41+
// 'An iteration starts when the cursor is set to 0,
42+
// and terminates when the cursor returned by the server is 0.'
43+
if (cursor === '0') {
44+
return console.log('Iteration complete');
3245
}
3346

3447
return scan();

0 commit comments

Comments
 (0)