-1

I'm having trouble with the following function:

function getLengthData(date, driverId) {
    var length = [];
    $
    .get('http://xx/x/x/' + date + '/' + driverId + '')
    .done(function (data) {
        var test = data.length;
        length.push(test);
    });
    return length;
}

This returns nothing while it should return an array with 1 element, the length of the data array. The next function uses the same way and works perfectly:

function getStopsFromStorage() {
    var stops = [];
    _2XLMobileApp.db.stopsData.load().done(function (result) {
        $.each(result, function () {
            stops.push(this.Id);
        });
    })
    return stops;
}

I kinda have an idea what the problem is but no idea how to fix.

Any help would be greatly appreciated!

Thx

4

2 回答 2

2

正如您已经了解的那样,您将无法使用return异步函数,例如$.get(). 接下来的return语句$.get()将在请求实际完成之前发生。

您可以做的一种选择是调整函数以接受它自己的回调。另一个是return延迟/承诺,因此调用代码可以应用回调本身。

更好的办法可能是同时支持like$.get()和其他Ajax 方法。

function getLengthData(date, driverId, callback) {
    return $.get('http://xx/x/x/' + date + '/' + driverId + '')
        .then(function (data) {
            return data.length;
        })
        .done(callback);
}
getLengthData('2013-07-31', '1234', function (length) {
    // use `length` here
});

getLengthData('2013-07-31', '1234').done(function (length) {
    // use `length` here
});

这个片段确实需要 jQuery 1.8+,因为它使用了.then(). 简而言之,return data.lengthwithingetLengthData只是更改任何进一步.done()回调的参数,例如callback.

示例:http: //jsfiddle.net/jMrVP/

于 2013-07-31T11:44:47.303 回答
0

你确定你的主机和端口匹配http://194.78.58.118:9001吗?

这可能是同源策略问题。

编辑:

AJAX异步JavaScript 和 XML。因此,您在从服务器获得响应之前返回值。

于 2013-07-31T11:11:57.907 回答