javascript - 使用 Node.js 将 http post 请求的异步响应获取到变量中

标签 javascript node.js asynchronous

我对 Javascript 还很陌生,正在尝试理解 Javascript 的异步概念。

我的目标是

responseStr = httpPost(parameters)
// then store responseStr in DB

但是,我可以做的 Javascript 是,

var callback = function(response) {
    var str = '';

    //another chunk of data has been recieved, so append it to `str`
    response.on('data', function(chunk) {
        str += chunk;
    });

    //the whole response has been recieved, so we just print it out here
    response.on('end', function() {
        console.log(str);
        });
    };

http.request(options, callback).end();

因此,我从上面的代码中将 http post 请求的响应获取到本地变量 str 中,但我仍然无法想象如何将其传递回我的 httpPost 调用者到 responseStr

基本上,流程是,

  • 在我的 httpPost 函数中,我通过 http.request 发送了 http 请求,
  • 并且它立即返回,
  • 不知何故,callback 函数逐位填充了 str 变量

但是,当一切完成后,如何将其传递回我的 httpPost 调用者到 responseStr 中,以便我可以将其存储起来?谢谢。

摘要:

谢谢所有回答的人。我非常喜欢你们的幽默感,为你们所有人点赞。

PS。分享a piece of comment I read the other day ,关于 Javascript 的异步性,

Today, we will examine four different methods of performing the same task asynchronously, in node.js...:

  1. In parallel, using callback functions
  2. Sequentially, using callback functions
  3. In parallel, using promises
  4. Sequentially, using promises

This will help you decide which to use for your particular situation. It is simply a matter of taste. If you want to know which is the best method -- the absolute best way to go -- is probably to switch to Golang.

:-)

最佳答案

您正在尝试做的事情存在一些问题。第一个问题是不可能从非阻塞函数返回仅在将来可用的值。不过别担心,一旦时间旅行成为可能,我们就不必再担心这个问题了:)但在那之前,我们该何去何从呢?我们可以采取一些措施来获取该值。

第一个(首选)解决方案是通过简单地将使用该值的所有功能移动到该值可用的位置来修改您的程序,例如回调。例如,假设使用 value 的唯一功能是函数调用 do_stuff_with(value)

// original program
var value = get_value('param', callback);
do_stuff_with(value);

// changes to
get_value('param', function (value) {
  do_stuff_with(value);
});

通常我从新程序员那里得到的答复是“哦不!这意味着我需要更改我的整个程序!我们还能做些什么吗?我不想更改代码。它很完美,现在是我家庭的一部分。你这个怪物!”我必须承认,这正是我在被提出同样的解决方案后的感受。对于这个问题,您可能想立即使用另一种解决方案,但它会极大地影响程序的性能。

成功从函数调用返回值的第二个解决方案(糟糕、天真,你会后悔的,不要这样做)要求您使用支持同步功能的方法。我只看到除 javascript 之外的所有语言的同步代码,因为 javascript 是单线程的。 “Blasphemy,这到底是什么意思?”这意味着整个 javascript 程序需要暂停整个过程以等待 http 请求完成。不打开新线程就无法打开 http 请求。那不好吗?是的,确实如此。这意味着整个用户界面将在 http 请求期间卡住。这意味着其他任务计划任务将不会按时调用。你知道玩一款一直卡住的电子游戏是什么感觉。太可怕了。

“但是我没有想象力,我真的很想写一个糟糕的程序。” - 很好,只需修改您的程序以使用实现同步功能的方法而不是采用回调的异步方法即可。我不知道从哪里得到这个,因为我从来没有需要过它。

// replace this method
var value = get_str_async_method('param', callback);
console.log(value) // undefined

// use one that is synchronous
// a callback is not needed for this method
var value = get_str_sync_method('param');
console.log(value); // reponse

关于javascript - 使用 Node.js 将 http post 请求的异步响应获取到变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48919782/

相关文章:

javascript - 期望选定的文本

javascript - 引用混淆赋值

javascript - 使用 Javascript 获取图像的 href 属性

javascript - 部署 Heroku 时应用程序崩溃(代码 h10)

c# - 使用异步/等待方法时使用存储库模式 Asp.NET MVC 5 EF

javascript - yam.platform.getLoginStatus 在没有 response.user 的情况下调用回调

javascript - Node 和/或套接字 io 多人打地鼠

node.js - Query.user 的类型必须是 Output Type 但得到 : undefined

c# - 单击按钮调用异步方法

javascript - async/await 中的执行顺序