【问题标题】:Refactor nested promises to a chain of promises将嵌套的 Promise 重构为 Promise 链
【发布时间】:2022-06-21 16:51:10
【问题描述】:

我已经简化了这个问题。我有 3 个函数,我想在每个函数之间运行 2 秒延迟。以下代码正在运行:

        $.when(one()).done(function () {
            $.when(delay(2000)).done(function () {
                $.when(two()).done(function () {
                    $.when(delay(2000)).done(function () {
                        $.when(three()).done(function () {
                            console.log('finished');
                        });
                    });
                });
            });
        });

    function delay(ms) {
        var waitForDelay = new $.Deferred();
        setTimeout(function () {
            waitForDelay.resolve().promise();
        }, ms);
        return waitForDelay.promise();
    }

    function one() {
        console.log('one');
        return new $.Deferred().resolve().promise();
    }

    function two() {
        console.log('two');
        return new $.Deferred().resolve().promise();
    }

    function three() {
        console.log('three');
        return new $.Deferred().resolve().promise();
    }

但是当我尝试重构它时,它不再等待延迟的时间:

$.when(one()).done(delay(2000)).done(two()).done(delay(2000)).done(three()).done(function () {
    console.log('finished');
});

同样稍作修改:

one().done(delay(2000)).done(two).done(delay(2000)).done(three).done(function () {
    console.log('finished');
});

如何重构以链接这些 Promise 而不是嵌套它们?

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    我的建议是不要使用 jQuery 奇怪的 promise-like 数据结构。

    让您的函数返回一个实际的Promise(显式地或通过使它们成为async functions)和await 链中的每个步骤。

    const delay = (ms) => new Promise((res) => setTimeout(res, ms));
    
    const one = async () => {
      console.log("one");
    }
    
    const two = async () => {
      console.log("two");
    }
    
    const three = async () => {
      console.log("three");
    }
    
    (async () => {
      await one();
      await delay(2000);
      await two();
      await delay(2000);
      await three();
      console.log("finished");
    })();

    【讨论】:

      猜你喜欢
      • 2018-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-24
      • 1970-01-01
      • 2019-05-19
      相关资源
      最近更新 更多