【问题标题】:Chain promises while condition is true条件为真时链式承诺
【发布时间】:2018-08-25 09:17:10
【问题描述】:

我正在尝试使用 JS Promise 获取通过 XHR 请求的所有页面。

对我来说,通过递归回调来实现这一点相对简单,但我如何通过 Promise 实现这一点?

没有承诺的简化示例:

class Foo {
    getPages(callback, pagesCount)
    {
        if (typeof(pagesCount) === 'undefined') {
            pagesCount = 0;
        }

        // Let's say its async XHR
        window.setTimeout(() => {
            ++pagesCount;
            // Let's say that in 90% of cases we will get a full page
            if (Math.random() < 0.9) {
                console.log('Page received!');
                this.getPages(callback, pagesCount);
            } else {
                console.log('Last page received!');
                callback(pagesCount);
            }
        }, 1000);
    }

    doStuff(pagesCount)
    {
        console.log('Total pages: ' + pagesCount);
    }

    run()
    {
        this.getPages(this.doStuff);
    }
}

(new Foo()).run();

我正在尝试实现以下目标:

class Foo {
    getPages()
    {
        ...
    }

    doStuff(pagesCount)
    {
        console.log('Total pages: ' + pagesCount);
    }

    run()
    {
        this.getPages().then(this.doStuff);
    }
}

(new Foo()).run();

【问题讨论】:

  • 这目前读作是一个教程的请求,这是你想要的吗?
  • 您可以在while 循环中使用await
  • 我把你的问题读了至少 4 遍,但还是没听懂。您可能会考虑添加一些示例来展示您想要的内容吗?
  • @jared-smith,我希望得到提示\文章或示例的链接\在这种情况下具有链接承诺的基本逻辑的代码的 sn-p \ 任何东西。我理解你的问题,我不是想用别人来解决我的问题,我只是想寻求帮助,因为已经尝试了几个小时没有成功地解决这个问题。
  • @SergeyNovikov 发布您的代码!我们可以帮助您编写代码,但在这里请求场外资源是题外话。

标签: javascript promise


【解决方案1】:

async/await 出现之前,递归承诺确实是不可能的。您必须将 Promise 转换为对回调友好的代码,并使用回调进行递归。

然而,async/await 允许你做你想做的事:

async getPages(pagesCount)
{
    if (typeof(pagesCount) === 'undefined') {
        pagesCount = 0;
    }

    // Let's say its async XHR
    while () {

        // Call promisified XHR like this:
        // xhrResult = await XHR();

        // Call callback based XHR like this: 
        // xhrResult = await new Promise(function(ok,err){
        //   XHR(function (error, result) {
        //     if (error) {
        //       err(error)
        //   } else {
        //       ok(result)
        //   }    
        // });

        if (Math.random() < 0.9) {
            console.log('Page received!');
            return await getPages(pagesCount);
        } else {
            console.log('Last page received!');
            return pagesCount;
        }
    };
}

注意:所有标记为async 的函数都会返回承诺。所以现在你可以这样做了:

getPages(100).then(count => console.log(count + ' pages left'))

【讨论】:

  • Before the advent of async/await recursive promises were indeed impossible - 我不同意
  • 有关系吗?
猜你喜欢
  • 2018-02-25
  • 2022-06-14
  • 2021-08-01
  • 2018-09-04
  • 2017-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多