Home > Blockchain >  How to return only one result when making a double await Node.js
How to return only one result when making a double await Node.js

Time:01-08

Hi I can´t find a solution to my problem of functions in cascade,

Service A

print(await serviceB.methodA(myParameter));

Service B

async methodA(MyParameter){

            return await methodB(MyParamter).then((value) =>{
                serviceA.methodC(value);
               }

            
         );
    }

So the output is

undefined
result 

How I can wait to the second result of the then?? Because when getting undefined is broking my service A

CodePudding user response:

Using your code structure, you need to return the inner promise.

Change this:

async methodA(MyParameter){
    return await methodB(MyParamter).then((value) =>{
        serviceA.methodC(value);
    });
}

to this:

async methodA(MyParameter){
    return methodB(MyParamter).then((value) =>{
        return serviceA.methodC(value);
    });
}

The result of the .then() becomes the resolved value of the promise chain. Since you weren't returning anything from the .then() handler, that resolved value became undefined.


But, since you're using async/await, it is generally better to not also mix .then() in the same code so I'd recommend changing to this:

async methodA(MyParameter){
    let value = await methodB(MyParamter);
    return serviceA.methodC(value);
}

CodePudding user response:

You are not returning nothing and this is why your print(methodA) is wrong, with these code it is gonna to work:

   async methodA(MyParameter) {
      return await methodB(MyParamter).then((value) =>
        serviceA.methodC(value).then((result) => {
          console.log("result");
          return result;
        })
      );
      console.log("hi");
    };
  •  Tags:  
  • Related