如何链接包含then和catch块的嵌套promise? [英] How to chain nested promises containing then and catch blocks?

查看:40
本文介绍了如何链接包含then和catch块的嵌套promise?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将嵌套在 Promise 中的 ES6 与每个 Promise 链接在一起,嵌套中的 then catch块?

How to chain ES6 nested Promises with each Promise in the nesting having then and catch blocks?

例如,什么是 Promise then catch 块链接实现,等效于以下嵌套的 AJAX 调用由成功 error 回调处理的实现,考虑到每个API调用都会返回一个 Promise ?

For example, what will be the Promise then and catch blocks chaining implementation equivalent for following nested AJAX calls implementation handled by success and error callbacks, considering every API call returns a Promise?

$.ajax({ 
    url: 'url1', 
    success: function() {
        console.log('URL1 call success');
        $.ajax({    
            url: 'url2',
            success: function() {
                console.log('URL2 call success');
            },
            error:function() {
                console.log('URL2 call error');
            }
         })
    },
    error: function() {
        console.log('URL1 call error');
        $.ajax({
            url: 'url3',
            success: function() {
                console.log('URL3 call success');
            },
            error:function() {
                console.log('URL3 call error');
            }
         })
    }})

推荐答案

如果您要链接承诺,则可以让每个处理程序返回一个承诺,然后链接 then catch从那里开始.我相信这可以说明您要做什么:

If you want to chain promises, you can have each handler return a promise, and then chain the then and catch functions from there. I believe this demonstrates what you're looking to do:

const getPromise = (time, reject=false) => new Promise((res, rej) => {
  setTimeout(() => reject ? rej() : res('done'), time);
});

getPromise(500)
  .then(() => {
    console.log('first response');
    return getPromise(500, false);
  })
  .then(() => {
    console.log('second response');
    return getPromise(500, true);
  })
  .catch((error) => {
    console.log('you can have catch statements return promises, too');
    return getPromise(700, true)
  })
  .then(() => {
    // this structure falls down here; is this a response to the promise returned from
    // the catch, or the promise returned from the 'second response' part?
    console.log('third response');
  })
  .catch(() => {
    console.error('hit an error');
  });

但是,重要的是要意识到这是一条没有分支逻辑的链.使用 handle success -> handle error -> handle success 的结构,一旦您的错误处理程序返回了有效的Promise,链中的其余部分将无法分辨之前发生的是成功还是错误处理程序的结果.这里没有分支逻辑,您需要嵌套promise才能实现.

However, it's important to realise that this is a chain with no branching logic. With the structure handle success -> handle error -> handle success, once your error handlers return valid promises, the remainder of the chain cannot tell whether what came before was a result of the success or error handlers. There's no branching logic here and you need nesting of promises to achieve that.

这里有两种主要的选择.首先,您可以抛出不同的错误类型,并在单个 catch 处理程序中处理每个不同的错误.其次,您可以改为使用 async / await 语法.两种方法都可以为您工作,但我认为他们应该提出一个单独的问题.

There are two main alternatives here. First you could throw different error types and handle each different error in a single catch handler. Second, you could use async/await syntax instead. Either may work for you but I think that they'd warrant a separate question.

这篇关于如何链接包含then和catch块的嵌套promise?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆