1

So I am trying to connect 2 new Promise with each other so I can send information to each other. So I want to use image.url which is made in the first promise be used in the second promise but when I want to call image.url it is undefined. Does anyone have an idea to make this work? (Btw there is nothing between the code just want to make an difference between the 2 Promise).

First Promise:

        image.promise = new Promise((resolve, reject) => {
          const formData = new FormData();
          formData.append('files', file);
          axios
            .post('http://api.resmush.it/', formData, { headers: { 'Content-Type': 'multipart/form-data' } })
            .then(response => {
              image.url = response.data.dest;
              console.log("The compressed image url: ", image.url)
            })
            .catch(() => reject());
        })
        .then(response => {
          image.status = STATUS_OK;
          image.savings = response.data.percent;
        })

Second Promise:

        image.promise = new Promise((reject) => {
        console.log(image.url);
        function downloadFile() {
          axios
            .get('http://par3.static.resmush.it/1e5b76fc993169757c1319c027f5dca3/insta_logo.jpg')
            .then(response => {console.log(response)})
            // .then(response => resolve(response))
            .catch(() => reject());
            // .catch(reject => {console.log(reject)})
        }

        downloadFile();
       }
  • [What is the explicit promise construction antipattern and how do I avoid it?](https://stackoverflow.com/q/23803743) – VLAZ Feb 23 '22 at 16:39

1 Answers1

1

I'm not sure to understand why you want to use this pattern, but if you want to make sure the second promise can have access to something defined in the first call, you'd have to make sure not to call the second promise before the first one has been resolved. Maybe something like this:

// ...
         axios
            .post('http://api.resmush.it/', formData, { headers: { 'Content-Type': 'multipart/form-data' } })
            .then(response => {
              image.url = response.data.dest;
              // not sure what you want to do here, I just pasted your code
              console.log(image.url);
              function downloadFile() {
                  axios.get('http://par3.static.resmush.it/1e5b76fc993169757c1319c027f5dca3/insta_logo.jpg')
                     .then(response => {console.log(response)})
                     // ...
              }

              downloadFile();
            })
Peterrabbit
  • 2,166
  • 1
  • 3
  • 19