Search code examples
javascriptflaskpromisefetch

Arrow function in Promise does not work with semicolon (Javascript)


I am using JS on my frontend to fetch data from a python flask backend.

fetch("/get_masks", {
            method : "POST",
            headers: {
                    'Content-Type': 'application/json'
                },
            body: JSON.stringify({"image_index" : 0})
        }).then(response => response.json()).then( data => {
                console.log(data["hello"]); 
            });

Flask:

@app.route("/get_masks", methods=["POST"])
def get_masks():
    
    return jsonify(hello="test")

This is working great, but if I add brackets and a semicolon into the response, it does not work anymore

.then(response => {response.json();}).then( data => {
                console.log(data["hello"]); 

Then "response" returns a undefined object.

Does someone know why this is happening?

Thank you in advance!


Solution

  • response => response.json() means response => { return response.json(); } for simplicity.

    So, if you want to use curly bracket, use return.

    .then(response => {
      return response.json();
    })
    .then( data => {
      console.log(data["hello"]);
    })