Nodemcu-firmware: Executing HTTP request followed by another HTTP request

Created on 19 Apr 2016  ·  4Comments  ·  Source: nodemcu/nodemcu-firmware

I wanted to execute a HTTP request (using http module) and when a response comes, immediately execute another request. The code is more or less is like this:

url = "http://google.com"

function firstRequest(callback)
  print("First request, connecting to " .. url)
  http.get(url, nil,
    function(code, data)
        print("First response: " .. code .. ", data: " .. data)
        callback()
    end)
end

function secondRequest()
  print("Second request, connecting to " .. url)
  http.get(url, nil,
    function(code, data)
        print("Second response: " .. code .. ", data: " .. data)
    end)
end


firstRequest(secondRequest)

Unfortunately the second request is never executed, in the output I always get:

First request, connecting to http://google.com
> First response: 302, data: ....
Second request, connecting to http://google.com

The response from the second request never comes back. What am I doing wrong?

I suspect that when the callback function of the first request is being executed it is not possible to "initiate" another HTTP request. If it is the cause, what is the proper way of achieveing such simple sequence of requests?

Most helpful comment

Hi @marcelstoer,

Thanks for your hint, it works!
I'm just wondering what is the explanation of such behaviour? I would like to avoid such pitfalls in the future...

All 4 comments

I suspect that when the callback function of the first request is being executed it is not possible to "initiate" another HTTP request.

I never tried myself but why not, have you tried? This all being asynchronous and event-driven I'd expect that to work just fine.

There is output of the script I attached, so don't you think it's very likely that I tried? 😉
If the callback is not an issue, what has to be done to make the above script work?

Grrr... mea culpa, sorry about that. I didn't study your example carefully enough and particularly had missed the last line (at that time I didn't think it was a complete example). Pity this seems to fall under #719 and should be discussed elsewhere.

If the callback is not an issue, what has to be done to make the above script work?

Replace callback() with node.task.post(callback) for example -> http://nodemcu.readthedocs.org/en/dev/en/modules/node/#nodetaskpost

Hi @marcelstoer,

Thanks for your hint, it works!
I'm just wondering what is the explanation of such behaviour? I would like to avoid such pitfalls in the future...

Was this page helpful?
0 / 5 - 0 ratings

Related issues

vsky279 picture vsky279  ·  7Comments

dicer picture dicer  ·  6Comments

liuyang77886 picture liuyang77886  ·  5Comments

marcelstoer picture marcelstoer  ·  4Comments

ShAzmoodeh picture ShAzmoodeh  ·  6Comments