0

I have two functions which are starting asynchronous loading of resources. How can I make them return promises to that I can wait until the loading is finished?

  // #1
  LoadMaps() {
    gFileService.getFile('syn-maps.json').then(
      mapItem => this.synMaps = mapItem
    ).then(
      gFileService.getFile('sense-maps.json').then(
        mapItem => this.senseMaps = mapItem
      )
    );
  }

  // #2
  LoadListAndMetadata() {
    gListService.getList().then(lexList => {
      let promises = [];
      lexList.forEach(lexItem => {
        lexItem.selected = false;
        this.lexList[lexItem.lexId] = lexItem;
        if (lexItem.hasMeta) {
          promises.push(gFileService.getFile(lexItem.metaFile).then(
            metaItem => this.metadata[lexItem.lexId] = metaItem
          ));
        }
      });
      $.when(...promises).then(
        () => $.templates('#lexSelectionTemplate').link('#lexSelection', this)
      );
    });
  }

I would like to get a Promise (or two) so that I can wait until both are finished, i.e. the files are loaded and the template is linked. I just don't see how I could obtain them so that they can be returned. Simply putting return in front of the first line of each function will not return the correct one for the nested tasks. Do I have to change my design here to be able to wait on the innermost tasks?

Felix Dombek
  • 13,664
  • 17
  • 79
  • 131

2 Answers2

1

Simply putting return in front of the first line of each function will not return the correct one for the nested tasks

Actually it will. Are you sure your put it on the first line of all four functions?

LoadMaps() {
  return gFileService.getFile('syn-maps.json').then(
//^^^^^^
    mapItem => this.synMaps = mapItem
  ).then(() => { // <== admittedly, you forgot this entire function
    return gFileService.getFile('sense-maps.json').then(
//  ^^^^^^
      mapItem => this.senseMaps = mapItem
    )
  });
}

LoadListAndMetadata() {
  return gListService.getList().then(lexList => {
//^^^^^^
    let promises = [];
    lexList.forEach(lexItem => {
      lexItem.selected = false;
      this.lexList[lexItem.lexId] = lexItem;
      if (lexItem.hasMeta) {
        promises.push(gFileService.getFile(lexItem.metaFile).then(
          metaItem => this.metadata[lexItem.lexId] = metaItem
        ));
      }
    });
    return Promise.all(promises).then(
//  ^^^^^^
      () => $.templates('#lexSelectionTemplate').link('#lexSelection', this)
    );
  });
}

Regarding LoadMaps, you might have been thinking in terms of running the two getFile calls concurrently. You can do that using Promise.all again:

LoadMaps() {
  return Promise.all([
//^^^^^^
    gFileService.getFile('syn-maps.json').then(mapItem =>
      this.synMaps = mapItem
    ),
    gFileService.getFile('sense-maps.json').then(mapItem =>
      this.senseMaps = mapItem
    )
  ]);
}

or even

LoadMaps() {
  return Promise.all([
    gFileService.getFile('syn-maps.json'),
    gFileService.getFile('sense-maps.json')
  ]).then(results => {
    [this.synMaps, this.senseMaps] = results
  });
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • OP could avoid the second return by un-nesting the the second then. – danh Jul 19 '17 at 02:53
  • @danh He could avoid the nesting, but not the return – Bergi Jul 19 '17 at 02:54
  • Ah ok, I only thought about the outer `return`s. If the inner functions return promises too, then the outer ones will wait for them automatically? – Felix Dombek Jul 19 '17 at 02:55
  • Wouldn't that first return return the whole chain? The last line of the ES6 function is implicit return, isn't it? – danh Jul 19 '17 at 02:55
  • 1
    @FelixDombek Yes, the `then` method [returns a promise for the result of the callback](https://stackoverflow.com/a/22562045/1048572) – Bergi Jul 19 '17 at 02:56
  • @danh Yes, it returns the last result from the whole chain, but that's what is expected, isn't it? Or maybe not the result value, `mapItem`, itself, but at least we'll want to wait for the assignment to happen. – Bergi Jul 19 '17 at 02:58
1

If all you need is to know when the last call has completed you can simply use this skeleton:

    function firstCall() {
        return new Promise((y,n) => setTimeout( () =>  y('firstCall'), 500 ));
    }

    function secondCall() {
        return new Promise((y,n) => setTimeout( () =>  y('secondCall'), 800 ));
    }

    function promiseTest() {
        Promise.all([
            firstCall(),
            secondCall()
        ]).then( function(data) {
            console.log( data );
        })
        .catch( function(err) {
           console.log( 'Error executing promisses.', err );
        });
    }
    promiseTest();
Jarek Kulikowski
  • 1,399
  • 8
  • 9