简体   繁体   English

如何在循环中正确使用 jQuery Deferred

[英]How to properly use jQuery Deferred inside of a loop

I'm trrying to call a function that loops through a dataset and updates values in that dataset from data that comes from an asynchronous function.我正在尝试调用一个循环遍历数据集的函数,并根据来自异步函数的数据更新该数据集中的值。 I obviously need to know when that function completes the loop and updates.我显然需要知道该函数何时完成循环和更新。

This is what I have currently:这是我目前拥有的:

function loadStationData() {
    var $dfd = $.Deferred();
    $.getJSON('../backend/navigation/get-stations.php', function(data) {
        stationData = data;
        $dfd.resolve();
    });
    return $dfd.promise();
}

function updateStationData() {
    var $dfd = $.Deferred();
    $.each(stationData, (i,v) => {
        var $dfd2 = $.Deferred();
        $.when(getFullCoordPack(v.lat, v.lng)).then(function(coords) {
            delete v.lat;
            delete v.lng;
            v.coords = coords;
            $dfd2.resolve();
        });
        return $dfd2.promise();
    });
    return $dfd.promise();
}

$.when(loadStationData(), updateStationData()).then(() => {
    // do stuff
});

The function getFullCoordPack(v.lat, v.lng) is using What3Words's API and therefore contains and AJAX call, hence requiring a promise when it completed.函数getFullCoordPack(v.lat, v.lng)使用 What3Words 的 API,因此包含 AJAX 调用,因此在完成时需要承诺。

However, I'm struggling to understand how to use the Deferred object in the second function and require some advice on how best to achieve my goal.但是,我很难理解如何在第二个函数中使用 Deferred 对象,并且需要一些关于如何最好地实现我的目标的建议。 The first function works just fine.第一个功能工作得很好。

$.getJSON already returns a promise, so there is no need to use a new Deferred for it. $.getJSON已经返回了一个 promise,所以没有必要为它使用一个新的 Deferred。

In the second function you don't have code that resolves $dfd .在第二个函数中,您没有解析$dfd的代码。

However, since ECMAScript 2015 there really is no good reason to still use jQuery Deferreds.然而,自 ECMAScript 2015 以来,确实没有充分的理由继续使用 jQuery Deferreds。 Now promises are native in JavaScript, together with async / await syntax, and APIs that return promises, like fetch .现在 promise 在 JavaScript 中是原生的,连同async / await语法,以及返回 promises 的 API,比如fetch

So something like this should work (assuming that getFullCoordPack returns a promise object):所以这样的事情应该有效(假设getFullCoordPack返回一个 promise 对象):

async function getStations() {
    const response = await fetch('../backend/navigation/get-stations.php'); 
    const stationData = await response.json();
    return Promise.all(stationData.map(async ({lat, lng, ...rest}) => ({
        ...rest,
        coords: await getFullCoordPack(lat, lng)
    })));
}

getStations().then((stationData) => {
    // do stuff with stationData
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM