Nodejs请求返回行为不端 [英] Nodejs Request Return Misbehaving

查看:116
本文介绍了Nodejs请求返回行为不端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题。我一直试图在过去的3个小时内解决这个问题,而且我不知道为什么这不起作用我是如何期待它的。请知道我仍然是Javascript的新手,所以如果有任何明显的事情,我会道歉。

I have a question. I've been trying to figure this out for the past 3 hours now, and I have no clue as to why this isn't working how i'm expecting it to. Please know that i'm still very new to Javascript, so I apologise if anything is blatantly obvious.

使用此代码,我正在尝试从中获取持有者令牌但是,Twitter,返回正文 console.log(正文)返回2个完全不同的东西。

With this code, i'm trying to get a bearer token from Twitter, however, return body and console.log(body) return 2 completely different things.

当我 console.log(正文)时,我得到了我期望的输出:

When I console.log(body), I get the output I expect:

{"token_type":"bearer","access_token":"#####"}

但是,如果我返回正文,我会将http请求作为JSON获取。我已粘贴下面的代码,希望有人能帮忙。

However, if I return body, I get the http request as JSON. I've pasted my code below, I hope someone will be able to help.

var request = require('request');

var enc_secret = new Buffer(twit_conkey + ':' + twit_consec).toString('base64');
var oauthOptions = {
    url: 'https://api.twitter.com/oauth2/token',
    headers: {'Authorization': 'Basic ' + enc_secret, 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
    body: 'grant_type=client_credentials'
};

var oauth = request.post(oauthOptions, function(e, r, body) {
    return body;
});

console.log(oauth)


推荐答案

异步,异步,异步。

您无法从函数返回异步操作的结果。该函数早在调用异步回调之前就已返回。因此,消耗 request.post()结果的唯一地方是在回调本身内部,并通过调用该回调中的一些其他函数并将数据传递给其他功能。

You cannot return the results of an asynchronous operation from the function. The function has long since returned before the asynchronous callback is called. So, the ONLY place to consume the result of your request.post() is INSIDE the callback itself and by calling some other function from within that callback and passing the data to that other function.

var oauth = request.post(oauthOptions, function(e, r, body) {
    // use the result here
    // you cannot return it
    // the function has already returned and this callback is being called
    // by the networking infrastructure, not by your code

    // you can call your own function here and pass it the async result
    // or just insert the code here that processes the result
    processAuth(body);
});

// this line of code here is executed BEFORE the callback above is called
// so, you cannot use the async result here

对于新的node.js / Javascript开发人员来说,这是一个非常常见的学习问题。要在节点中编码,您必须学习如何使用这样的异步回调。

FYI, this is a very common learning issue for new node.js/Javascript developers. To code in node, you have to learn how to work with asynchronous callbacks like this.

这篇关于Nodejs请求返回行为不端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆