How to get return value from stub function?

Viewed 121

Using grpc, i create a stub 'client'. He has an 'auth' method. I call like that

client.auth({uuid:cookies.uuid}, function(err, r){} );

The function in the parameter will be called asynchronously, but I need to get its value synchronously. How can this be done?

2 Answers

Is impossible to convert an asynchronous method to a synchronous one. You can "simulate" it vanilla with async/await and promises, without any external package.

function clientLogin() {
    return new Promise((accept, reject) => {
        client.auth({uuid:cookies.uuid}, (err, r){
            if (err) {
                reject(err);
            } else {
                accept(r);
            }
        });
    });
}

// This code needs to run inside and async function
try {
    let r = await clientLogin();
    console.log(r);
} catch (e) {
    console.error(e);
}

clientLogin() returns a Promise that will be resolved later in the future (AKA asynchronous). With the await keyword you can tell JavaScript to wait for the Promise to resolve before continuing with the execution, so is a simulated synchronous code, although is not really syncrhonous.

If you are not used to async/await, is a bit long to explain, so better look for a tutorial.

That is an asynchronous operation. You can't make it complete synchronously. You could use a library like grpc-promise or grpc-caller to get a promise, and then use await to be able to code in a similar style to synchronous code.

Related