return value from nodejs function

Please, help me I have a script

export    function GetKey(inn, res) {
    try {
        const body = {
            7709798583: {
                name: 'someName',
                key: '123'
            },
            7718266352: {
                name: 'otherName',
                key: '123'
            }
        };
    res(body[inn]['key']);

    } catch (err) {

       res('0000000000000');
    }
};

In other file I try to use this function

GetKey(param, (name) => {
            console.log(name);
        });

It's ok. but I need to return callback to the parametr. How?

 var param =  GetKey(param, (name) => {
            return name;
        });

is not correct and return undefined

Upvotes: 0

Views: 201

Answers (1)

Kevin Ghadyani
Kevin Ghadyani

Reputation: 7287

That's not how callbacks work; although, you can fake that behavior using Promise and async-await syntax.

If you want to write your code like you have it, you'll want to put the rest of your logic in a function and pass it directly to your callback:

var param = ''

var allYourLogic = name => {
    // YOUR LOGIC
    param = name
}

GetKey(param, allYourLogic);

Or you can simply inline your logic:

GetKey(param, (name) => {
    param = name
    // YOUR LOGIC
});

Using the Promise syntax, this is how it looks:

new Promise(resolve => {
    GetKey(param, resolve)
})
.then(name => {
    param = name
    // YOUR LOGIC
})

Lastly, using the async-await methodology:

var param = (
    await new Promise(resolve => {
        GetKey(param, resolve)
    })
)

Really though, it seems like you're doing something wonky which is why you're running into this issue in the first place.

Your entire application will act like it's asynchronous as soon as you use a callback because the callback doesn't execute immediately in Node.js's event loop. Instead, the current function you're in will finish executing before the GetKey function calls the callback method.

Upvotes: 4

Related Questions