Adam Katz
Adam Katz

Reputation: 6964

Confusion with promises

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')        
    });
 }

Upvotes: 1

Views: 68

Answers (1)

Amadan
Amadan

Reputation: 198294

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).

Upvotes: 2

Related Questions