for loop over event driven code?

前端 未结 3 1286
孤街浪徒
孤街浪徒 2021-01-21 23:18

In a redis datastore I have a list of keys, I want to iterate over that list of keys and get those values from redis. The catch is I am using an event driven language, javascri

3条回答
  •  旧巷少年郎
    2021-01-21 23:37

    ??? how to block until finished ???

    You can't, not if the calls you're making are asynchronous. You have to define your getAll with the expectation it will complete asynchronously, then recast it a bit.

    I'm not familiar with the redis calls you're making, but the fundamental pattern is:

    function doTheBigThing(param, callbackWhenDone) {
        asyncCallToGetList(param, function(result) {
            var list = [];
    
            asyncCallToGetNextEntry(result.thingy, receivedNextEntry);
    
            function receivedNextEntry(nextResult) {
                if (nextResult.meansWeAreDone) {
                    callback(list);
                }
                else {
                    list.push(nextResult.info);
                    asyncCallToGetNextEntry(result.thingy, receivedNextEntry);
                }
            }
        });
    }
    

    Breaking that down:

    1. doBigThing (your getAll) is called.
    2. It does the "get the list" call, passing in the function to use as the callback when we have the list or list handle or whatever.
    3. That callback defines a function, receivedNextEntry, and calls the "get the next entry" function with whatever info is used to retrieve the entry, passing that in as a callback.
    4. receivedNextEntry stores the entry it got and, if done, fires the main "all done" callback; if not, it issues the next request.

    Sorry not to be able to give you a redis-specific answer, but I think the mappings are:

    • doBigThing = getAll
    • asyncCallToGetList = redis.lrange
    • asyncCallToGetNextEntry = redis.hgetall

    ...but what the parameters are you use with redis.lrange and redis.hgetall I'm afraid I don't know.

提交回复
热议问题