DEV Community

.
.

Posted on

console.time(), parsing api response as json and a little test python server

I wanted to set up a fake API that gives me test data and find out how long does my javascript function (that is wrapped deep inside some react components) execute.

Python - fake API

server.py:

from flask import Flask, jsonify
from flask_cors import CORS

app = Flask(__name__)
cors = CORS(app)
@app.route('/get-data', methods=['GET'])
def get_data():
    data = getData() # generate fake data, much bigger than real
    return jsonify(data)


if __name__ == "__main__":
    app.run()

Enter fullscreen mode Exit fullscreen mode

Javascript - index.html

<html>
<body>
<script>
function doExpensiveThings() {
   ...
}

fetch('http://localhost:5000/get-data', {mode: 'cors'}).then(response => {
    response.json().then(jsonResponse => {
        console.time("doExpensiveThings");
        doExpensiveThings(jsonResponse);
        console.timeEnd("doExpensiveThings");
    }).catch(err => {
        console.warn(err);
})
}).catch(err => {
    console.warn(err);
})

</script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

And then in the console, one would see: doExpensiveThings: 1.3291015625 ms.

fetch returns a promise, if everything went alright, the promise is resolved and the value is an instance of the Response class. I wanted to parse the response as json, so I called .json() method on the instance, this again returns a promise.

Top comments (0)