Pergunta

Odd question I guess...

I'm building my DOM in memory and make heavy use of promises. Say I have this inside a for... loop:

target = document.createDocumentFragment();
promises = [], pass, skip, store;

for (i = 0; i < foo; i += 1) {
    element = foo[i];

    // set promise
    promises[i] = app.setContent(element, {}, update)
        .then(function(response) {
            // HELP!
            if (pass) {
              target.appendChild(store)
              store = undefined;
              skip = undefined;
              pass = undefined;
            }
            if (response.tagName !== undefined) {
              pass = true;
            }
            if (skip === undefined && response.tagName === undefined) {
              store = response;
              skip = true;
            } else {
              target.appendChild(response);
            }
          });

  RSVP.all(promises).then(continue...

The loop above runs 3x returning two div tags and a documentFragment. Without promises, no problem, my structure is

 <div toolbar>
 <fragment = form>
 <div toolbar>

Problem is, when I converted to async I have no more say in the order items get appended forcing me to stupid things as above, where I'm finding my fragment, store it in store, set a skip parameter, append my first div, which sets pass, which will allow my stored fragment to be appended when the next promises "comes in"... what a waste of code...

Question:
Is there any way to properly set the order of items in a generic way when all items are being returned async? If not, how do I move items? Since I'm working in memory, I can select using querySelector/qsAll but I don't have a lot of other options? Any ideas?

(And please don't suggest to put in the DOM and then shuffle :-))

Thanks!

Foi útil?

Solução

I'll explain in words ...

On making each async request, also create a container, in the right place, for the requested data to go when it eventually arrives. This container will typically be a <div> or a <span>.

Keep a reference to the container (typically in a closure) such that the async response handler knows which container corresponds to which data.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top