Cutehacks / duperagent

A QML clone of VisionMedia's SuperAgent module.
MIT License
56 stars 23 forks source link

Can't iterate from a Response Body #4

Closed neftalyluis closed 8 years ago

neftalyluis commented 8 years ago

When i'm trying to get the value from a array of json objects using a for loop i dont get nothing, not even an undefined, but accesing them like res.body[0].title it does.

¿Is there a workaround for this behavior?

Here's the snippet: https://gist.github.com/neftalyluis/1e3abaa7a870cda2476effe73c30588f

And the JSON i get from the request it's like: http://jsonplaceholder.typicode.com/posts

Thanks in advance (:

jrbarron commented 8 years ago

@neftalyluis The problem is that you are omitting the var keyword in the declaration of i inside the for loop. This is not valid in QML because without the var you are creating a global variable which is not permitted in QML Javascript's engine. The fix is quite simply to add var like so:

    for (var i = 0; i< res.body.length; i++){
        console.log(i)
        console.log(res.body[i].title)
    }

You can verify this by testing with a normal test case:

        var a = [1, 2, 3, 4];
        for (i = 0; i < a.length; i++) {
            console.log(a[i]);
        }

The above will result in an error:

Uncaught exception: Invalid write to global property "i"

In the case of Duperagent, the exception is being thrown from inside an asynchronous callback and it looks like we currently ignore the result internally. I'll add a check for an error here and dump it to the console. Thanks for the report!