【问题标题】:wait for a javascript function to return等待一个javascript函数返回
【发布时间】:2018-04-30 12:38:11
【问题描述】:

我正在做一个对服务器进行同步 ajax 调用的函数。 问题是当我调用函数时,main 不等待数据传播。

我更好地解释自己:

我需要从函数中返回一些数据:

var firstdate = getLastPaycheck();

这个函数是:

function getLastPaycheck() {
    let returnValue  = sessionStorage.getItem('last_paycheck');

    if (returnValue == "" || returnValue == null) {
        const message = { "cookie": getCookie("userCookie") };
        var xhr = new XMLHttpRequest();
        xhr.addEventListener('load', complete, false);
        xhr.open("POST", '/getLastPaycheck', false);
        xhr.setRequestHeader("Content-type", "application/json");
        xhr.send(JSON.stringify(message));

        function complete(e) {//Call a function when the state changes.
                const response = JSON.parse(xhr.responseText);
                console.log("Value taken from the server");
                returnValue = moment(response.value[0].last_paycheck).format(getDateFormat("iso"));
                return returnValue;
            console.log("Returned value");
            } // if readyStatus = 200;

    } else {
        console.log("Value taken from the session");
        return returnValue;
    }
}

问题是从服务器获取数据时,“firstdate”的值总是未定义。

有人可以解释一下怎么做吗?

谢谢。我很欣赏它。

【问题讨论】:

  • 您的连接可能是同步的,但您仍然依赖于事件,而事实并非如此。此外,回调函数内部的 return 语句不会触发外部函数的返回。

标签: javascript ajax synchronization return


【解决方案1】:

你也可以使用回调来做到这一点:

    function getLastPaycheck(callback) {
        let returnValue  = sessionStorage.getItem('last_paycheck');

        if (returnValue == "" || returnValue == null) {
            const message = { "cookie": getCookie("userCookie") };
            var xhr = new XMLHttpRequest();
            xhr.addEventListener('load', complete, false);
            xhr.open("POST", '/getLastPaycheck', false);
            xhr.setRequestHeader("Content-type", "application/json");
            xhr.send(JSON.stringify(message));

            function complete(e) {//Call a function when the state changes.
                    const response = JSON.parse(xhr.responseText);
                    console.log("Value taken from the server");
                    returnValue = moment(response.value[0].last_paycheck).format(getDateFormat("iso"));
                    callback(returnValue);
                console.log("Returned value");
                } // if readyStatus = 200;

        } else {
            console.log("Value taken from the session");
            callback(returnValue);
        }
    }

    getLastPaycheck(function(data) {
      // data is accessible here
    });

【讨论】:

  • 嗨,谢谢,但似乎不起作用:/ 我做了 getLastPaycheck(function (data) { startdate.value = data; });但它似乎不起作用。这是我制作的函数: function getLastPaycheck(callback) { let returnValue = sessionStorage.getItem('last_paycheck'); ...
  • 嗯,这可能是因为它没有进入 if 语句。在 else 里面,也做回调(returnValue)。检查编辑。
  • 好的!它有效,我忘了用“回调”更改“返回”!非常感谢,我有一杯酒!
【解决方案2】:

你可以使用ES6 async-await然后直接调用

var firstdate = await getLastPaycheck();

【讨论】:

    猜你喜欢
    • 2011-03-04
    • 2019-02-20
    • 1970-01-01
    • 2016-10-16
    • 1970-01-01
    • 2017-10-03
    • 2017-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多