gpt4 book ai didi

Javascript 重用 Promise 来管理多个调用

转载 作者:行者123 更新时间:2023-12-03 01:26:51 25 4
gpt4 key购买 nike

使用 jQuery promise ,我会执行以下操作来管理以下情况:我有多个需要调用外部资源的实例,但我不想多次调用相同的外部资源。

  1. 初始 REST 调用获取多个数据对象,其中包含对其他信息的引用(在示例中,“部门”属性提供了我可以在哪里找到有关部门的更多信息的引用)。

{ "somedata": "...", "department": "https://api.../departments/1000", }

  • 在每个数据对象的单独函数调用的深处,我希望协调对相同资源的所有调用。我不想多次获取“department 1000”的部门名称。

  • 我将 Promise 或返回的结果保存在字典中并重用它们。

    a.如果它是一个 promise ,我将返回相同的 promise 以供调用者重用。

    b.如果它是获取的值,我会使用超时异步解析 promise 。

  • 这是代码:

    var Departments = {};

    function getDepartmentName(id){
    var dfd = new $.Deferred();
    var promise = dfd.promise();

    if(id in Departments){
    if(typeof Departments[id] == 'object'){
    return Departments[id];//reuse the promise
    }else{//department name is a string
    setTimeout(function(){ dfd.resolve(Departments[id]); }, 0);
    }
    }

    else{
    Departments[id] = promise;//Set dictionary value to the promise
    var dPromise = FetchDepartment('https://api.../departments/'+id);
    $.when(dPromise).then(
    function(departmentName){
    Departments[id] = departmentName;//Re-set dictionary value to the fetched value
    dfd.resolve(departmentName);
    },
    function(err){
    delete Departments[id];
    dfd.reject('Call failed');
    }
    );
    }
    return promise;

    }

    这似乎可行,但我担心这是否是一个很棒的设计。我有几个问题。

    1. 我应该使用一些 Promise 功能吗?
    2. 是否存在某些情况下事情可能会以错误的顺序发生?
    3. 重用这样的 Promise 实例是否正确?多个调用者调用同一个 Promise 对象的 .then,它似乎工作得很好,但我不知道当 Promise 得到解决时 jQuery 如何链接所有这些接收者。

    最佳答案

    I save promises OR a returned result in a dictionary and reuse them. If it is a fetched value, I resolve the promise asynchronous by using a timeout.

    别把事情搞得这么复杂。这与您只是遵守 promise 并仅返回它完全相同,而不是在第一个 promise 履行后为调用创建新的 promise 。

    此外,avoid deferreds当你已经在处理 promise 时。

    var Departments = {};

    function getDepartmentName(id) {
    if (id in Departments){
    return Departments[id]; //reuse the promise
    } else {
    var promise = FetchDepartment('https://api.../departments/'+id).then(null, function(err){
    delete Departments[id]; // allow retries
    throw err;
    });
    return Departments[id] = promise;
    }
    }

    Is it correct to reuse a promise instance like this, where multiple callers make a call to .then of the same promise object?

    是的,这完全没问题。它们的回调将按照与 then 的原始调用相同的顺序进行安排。

    关于Javascript 重用 Promise 来管理多个调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51496010/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com