简体   繁体   English

从nodejs函数返回值

[英]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 不正确,返回未定义

That's not how callbacks work; 回调不是这样工作的。 although, you can fake that behavior using Promise and async-await syntax. 但是,您可以使用Promise和async-await语法来伪造该行为。

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: 使用Promise语法,其外观如下:

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. 一旦使用回调,您的整个应用程序将表现为异步状态,因为该回调不会立即在Node.js的事件循环中执行。 Instead, the current function you're in will finish executing before the GetKey function calls the callback method. 相反,您所在的当前函数将在GetKey函数调用回调方法之前完成执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM