HamidArrivy HamidArrivy - 1 year ago 146
React JSX Question

How to use Promise.all in react js ES6

What i want to do is to upload file on server, then get URL of uploaded file and preview it. Files can be more than one. For that purpose i have written following code:

let filesURL=[];
let promises=[];
if(this.state.files_to_upload.length>0) {

for(let i=0; i<this.state.files_to_upload.length; i++) {
promises.push(this.uploadFilesOnServer(this.state.files_to_upload[i]))
}

Promise.all(promises).then(function(result){
console.log(result);
result.map((file)=>{
filesURL.push(file);
});
});
console.log(filesURL);
}
const uploadedFilesURL=filesURL;
console.log(uploadedFilesURL);


console.log(filesURL);
give me the values returned by
Promise.all
.

And i want to use these values only when
Promise.all
completes properly. But, i am facing problem that lines
console.log(uploadedFilesURL);
excutes first irrespective of
Promise.all
and give me
undefined
values.I think i am not using promises correctly, can anyone please help me?

uploadFileOnServer
code is:

uploadFilesOnServer(file)
{
let files=[];
let file_id='';

const image=file;
getImageUrl().then((response) => {
const data = new FormData();
data.append('file-0', image);
const {upload_url} = JSON.parse(response);
console.log(upload_url);

updateProfileImage(upload_url, data).then ((response2) => {
const data2 = JSON.parse(response2);
file_id=data2;
console.log(file_id);
files.push(file_id);
console.log(files);
});
});
return files;
}

Answer Source

No, promise is asynchronous and as such, doesn't works the way you thinks. If you want to execute something after a promise completed, you must put it in a promise then callback. Here is the example based on your code:

uploadFilesOnServer(file) {
  let files=[];
  let file_id='';

  const promise = getImageUrl()
  .then((imageUrlResponse) => {
    const data = new FormData();

    data.append('file-0', image);

    const { upload_url }  = JSON.parse(imageUrlResponse);

    console.log(upload_url);

    return updateProfileImage(upload_url, data);
  })
  .then ((updateImageResponse) => {
    file_id= JSON.parse(updateImageResponse);

    console.log(file_id);

    files.push(file_id);

    console.log(files);

    return files;
  });

  return promise;
}

let filesPromise = Promise.resolve([]);

if(this.state.files_to_upload.length > 0) {
  const promises = this.state.files_to_upload.map((file) => {
    return this.uploadFilesOnServer(file);
  });

  filesPromise = Promise.all(promises).then((results) => {
    console.log(results);

    return [].concat(...results);
  });
}

// This is the final console.log of you (console.log(uploadedFilesURL);)
filesPromise.then((filesUrl) => console.log(filesUrl));

A good book to read about ES6 in general and Promises in particular is this book Understanding ECMAScript 6 - Nicholas C. Zakas

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download