如何 return 在进行双重等待时只有一个结果 Node.js

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

嗨,我找不到解决级联函数问题的方法,

服务 A

print(await serviceB.methodA(myParameter));

服务 B

async methodA(MyParameter){

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

            
         );
    }

所以输出是

undefined
result 

我怎么能等到第二个结果呢??因为当未定义时会破坏我的服务 A

使用您的代码结构,您需要return 内部承诺。

改变这个:

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

到这个:

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

.then() 的结果成为承诺链的解析值。由于您没有从 .then() 处理程序中 returning 任何内容,因此解析后的值变为 undefined.


但是,由于您使用的是 async/await,通常最好不要在同一代码中混合使用 .then(),因此我建议更改为:

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