1

I am getting stuck with trying to get JavaScript promise to work as intended.

My code:

var p = new Promise(function(resolve, reject) {
      for (var i = 0; i < pics_needed.length; i++) {
        download_pics(pics_needed[i])
      }
      for (var i = 0; i < partners_pics_needed.length; i++) {
        partners_download_pics(partners_pics_needed[i])
      }
      resolve('Success!');
    })
    p.then(function() { 
      AsyncStorage.setItem("database",responseText)
      AsyncStorage.removeItem("time")
      alert ("Success! \nYour update has been installed.")
      go()

    });

Both functions that are called in the for loop download pictures from a server. The problem is, the p.then part of the function is running before all the pictures are downloaded. How can I alter this so that the p.then part happens after all the downloading is complete?

What the functions do:

function download_pics (id){

 var path = RNFS.DocumentDirectoryPath + '/' + id + '.jpg';
 fetch('address of server ='+id)
  .then((response) => response.text())
   .then((responseText) => {
     var pic_object = JSON.parse(responseText)
     RNFS.writeFile(path, pic_object.response, 'base64')        
    });
 }
Zong
  • 6,160
  • 5
  • 32
  • 46
Adam Katz
  • 6,999
  • 11
  • 42
  • 74
  • 2
    Your promise resolves immediately, the real question, that you have to show us, is what the `download_pics` and `partners_download_pics` functions does, or more specifically, what they return. – adeneo Apr 21 '16 at 01:46
  • Okay I am updating question – Adam Katz Apr 21 '16 at 01:48
  • 1
    @adeneo: This is a rhetorical question, right? :) We know what we will find there: an asynchronous operation that is not chained as a promise. – Amadan Apr 21 '16 at 01:50
  • This looks a lot like the [`Promise` constructor antipattern](http://stackoverflow.com/q/23803743/1048572). And you somehow seem to have expected any asynchronous code invoked from the `Promise` callback to be implicitly awaited? Nope, [promises are no magic](http://stackoverflow.com/a/22562045/1048572). – Bergi Apr 21 '16 at 02:02

1 Answers1

2

As hinted in the comments - promises are not worthless if you're going to go behind their backs.

function download_pics (id){
 var path = RNFS.DocumentDirectoryPath + '/' + id + '.jpg';
 return fetch('address of server ='+id)  // <--- NOTE: return here
  .then((response) => response.text())
   .then((responseText) => {
     var pic_object = JSON.parse(responseText)
     return RNFS.writeFile(path, pic_object.response, 'base64') // <-- and here
    });
 }

and then

  var pics_promises = pics_needed.map(function(pic) {
    return download_pics(pic);
  });
  var partners_pics_promises = partners_pics_needed.map(function(pic) {
    return partners_download_pics(pic);
  });
  return Promise.all(pics_promises.concat(partners_pics_promises));

EDIT: added the RNFS.writeFile to the promise chain per @adeneo (I'm not familiar with RNFS).

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • Note that `RNFS.writeFile` *(React)* is async as well, not sure if the OP needs to wait for the files to be written though – adeneo Apr 21 '16 at 01:54
  • @adeneo: Good point! If so, that needs to be promisified as well. – Amadan Apr 21 '16 at 01:55
  • Unfortuanately that is correct, I clearly have a mountain to learn with regard to this. – Adam Katz Apr 21 '16 at 01:56
  • It's React, so it already returns a promise, one can do `RNFS.writeFile(args).then(() => ...` etc. but as it's inside the outer promise callback it should return to that – adeneo Apr 21 '16 at 01:56
  • Basically, JS almost never does IO synchronously, unless you explicitly want it to. Every time you handle a promise, you need to do something with it (e.g. using `then` or `Promise.all` or `return`); you can't afford to ignore it. – Amadan Apr 21 '16 at 01:59
  • I have clearly still done something wrong as now the code never gets to the p.then section – Adam Katz Apr 21 '16 at 02:11
  • It appears that the function as I copied from you is getting stuck at the first return and not going any further and therefore not completing the promises and therefore never getting to the p.then part – Adam Katz Apr 21 '16 at 02:42
  • Sorry, I probably can't get the details right, since I've never worked with `RNFS`. – Amadan Apr 21 '16 at 03:33