为什么我的函数没有从 fetch 中获取结果?

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

我有一个调用另一个函数 (post) 的函数 (requestLogin),它使用 fetch 从服务器获取一些 JSON。

post 函数工作正常,但 return JSON 对象没有返回到 requestLogin。任何建议表示赞赏。

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

获取 API returns 一个 Promise,它由您的 post 函数返回。

您应该处理函数返回的承诺,而不是使用回调来处理结果。

例如:

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

此过程与您的过程相同,但您在 requestLogin 函数中以错误的方式使用了回调。您需要在 post 函数中访问 callBack 方法参数并传递 json 结果到 callBack 方法

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