Search code examples
javascriptreactjses6-promise

Why isn't my function getting the result from fetch?


I have a function (requestLogin) that calls another function (post) which uses fetch to obtain some JSON from a server.

The post function work fine, but doesn't return the JSON object back to requestLogin. Any suggestions appreciated.

function post(path = "", json = "") {

    let url = "/" + path;

    return fetch(url, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: json,
    })
    .then(response => response.json())
    .then(json => {
        console.log("*** RESULT=");
        console.log(json);
        return json;
    });
}


function requestLogin(path, mobile, pwd) {

    let data = {
        "mobile": mobile,
        "pwd": sha256(pwd)
    }
    let json = JSON.stringify(data);

    post(path, json, (result2) => {
        console.log("*** RESULT2=" + result2);
        if (result2.result === 'ok') {
            console.log("server json return valid result")
        }
    });
}

Solution

  • The fetch API returns a Promise, which is returned by your post function.

    Instead of using a callback to handle the results, you should process the promise returned by the function.

    For example:

    post(path, json).then((result2) => {
      console.log("*** RESULT2=" + result2);
      if (result2.result === 'ok') {
        console.log("server json return valid result")
      }
    });