MagneticScrolls
MagneticScrolls

Reputation: 23

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")
        }
    });
}

Upvotes: 2

Views: 108

Answers (2)

iambinodstha
iambinodstha

Reputation: 1007

this process is same as yours but you are using callback in wrong way in requestLogin function. you need to access that callBack method parameter in post function and pass json result in callBack method

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

    let url = "/" + path;

    return fetch(url, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: json,
    })
    .then(response => response.json())
    .then(json => {
        //passing json result in callBack method instead of returning
        callBack(json);
    });
}


function requestLogin(path, mobile, pwd) {

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

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

Upvotes: 0

natsuozawa
natsuozawa

Reputation: 660

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")
  }
});

Upvotes: 1

Related Questions