0

I am calling one API "getProjectListForInstance" and getting result in response which is an array of objects. Like this :

[ { "_id": "uyuyiuyiuy", "project_name": "Project1", }, { "_id": "hjhjhjhjkh", "project_name": "Project2", } ]

   return new Promise((resolve, reject) => {
          RESTService.getProjectListForInstance(previousInstance)
          .then((result) => {
            this.copyProjectInfo(result);
          });
        });

Now using above result in below code.

  copyProjectInfo(projects) {
        console.log('copyProjectInfo');             
      
        return new Promise((resolve, reject) => {
            RESTService.createProjectInfoForNewInstance(projects)
            .then((result) => {
              console.log("Successfully done");
              console.log(result);
            }); 
        });
      },

The above code is not working. Getting 502 but when I am creating an array in code itself like below, then it is working fine.

copyProjectInfo(projects) {
      console.log('copyProjectInfo');             
      let details = 
        [
          {
           "_id": "uyuyiuyiuy",
           "project_name": "Project1",
           },
          {
           "_id": "hjhjhjhjkh",
           "project_name": "Project2",
         }
       ];
        return new Promise((resolve, reject) => {
            RESTService.createProjectInfoForNewInstance(details)
            .then((result) => {
              console.log("Successfully done");
              console.log(result);
            }); 
        });
      },

Do I need to cast the Object received from first API before using it as an input for second API? and How?

Thanks, Jyoti

Jyoti
  • 2,065
  • 3
  • 25
  • 28
  • 1
    You should remove those Promise constructors and return the Promise from the `RESTService` methods directly. This is known as a [Promise Constructor anti-pattern](https://stackoverflow.com/questions/23803743/3068190). Make sure to use [`catch()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch) to handle any errors too. – samthecodingman Aug 05 '21 at 14:06

1 Answers1

0

I think you can try to use async/await syntax to do the jobs. I also remove all the unnecessary Promises wrapper.

example below:

(async function run() {
  try {
    const projects = await RESTService.getProjectListForInstance(
      previousInstance
    );

    const result = await RESTService.createProjectInfoForNewInstance(projects);

    console.log(result);
  } catch (err) {
    console.log(err);
  }
})();
ikhvjs
  • 5,316
  • 2
  • 13
  • 36