【问题标题】:How to extract the value of a variable outside Nodejs callback function如何在Nodejs回调函数之外提取变量的值
【发布时间】:2019-07-23 19:44:29
【问题描述】:

我无法获取回调代码之外的响应值。它在外部返回未定义,而在回调中它给出了正确的结果。

function doCall(urlString, callback) {
    request.get(
        urlString,
        null,
        null,
        (err, data, result) => {                              
            var statusCode = result.statusCode;
            return callback(data);
        }
    );
}

const apiResponse = doCall(urlString, function(response) {
    console.log('***************************' + response); //Prints correct result
    return JSON.parse(response);
});

console.log('+++++++++++++++++++++++++' + apiResponse); //Prints undefined

【问题讨论】:

  • 你需要使用 promise 或 async/await
  • 您的函数doCall 不返回任何内容,因此将其返回“值”影响到apiResponse 会将其值设置为undefined
  • 但 doCall 正在返回“返回回调(数据)”。但这不正确吗?
  • @Jeff 如何使用 async 帮助我获得函数之外的值。
  • 您需要了解事件循环和异步在节点中的工作方式。您需要从承诺中设置类似 var response = await getResponse() 的内容。

标签: node.js variables callback scope request


【解决方案1】:

function doCall(urlString) {
    return new Promise((resolve, reject) => {
        request.get(
            urlString,
            null,
            null,
            (err, data, result) => {
                if (error) reject(error);
                var statusCode = result.statusCode;
                resolve(data);
            });
    });
}

async function myBackEndLogic() {
    try {
        const result = await doCall(urlString);
        console.log(result);
       //return JSON.parse(result) if you want

    } catch (error) {
        console.error('ERROR:');
        console.error(error);
    }
}

myBackEndLogic();

Read this for more explanations

【讨论】:

  • 非常感谢您分享这个。我能够运行代码。
  • 欢迎。阅读我提供的链接。这将有助于消除 nodejs 中的许多困惑。
  • 我也强烈推荐 Udemy 上的这门课程 (udemy.com/the-complete-nodejs-developer-course-2)。即使你有很好的编程背景,它也涵盖了很多与 nodejs 不同/独特的东西。
  • 谢谢杰西和杰夫。链接非常有用。我很感激。谢谢!
【解决方案2】:

如果您想要同步的代码,请将所有内容包装在异步函数中:

(async (){
    async function doCall(urlString, callback) {
        return await request.get(urlString, null, null); // or store in a variable and return modified response
    }
    const apiResponse= await doCall(urlString, (response) => {
        console.log('response', response);
        return JSON.parse(response);
    });
    console.log('apiResponse', apiResponse);
})()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-18
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多