本文介绍了ES6 Promises/在实现多个Promise后调用函数(不能使用Promises.all)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写Javascript,该Javascript需要按以下顺序发生这些事件:

  1. 同时触发多个API调用
  2. 所有呼叫完成并且响应返回后,执行一行代码

听起来很简单,但棘手的是我不能使用Promises.all(),因为我仍然希望在所有诺言都实现,成功或失败之后执行该行代码.除非我对Promises.all()有误解,否则一个失败将导致代码行无法在then()中执行,而在error()中执行得太早.

我很可能会丢失一些显而易见的东西,但是我能看到的另一种方法是将API调用promise链接在一起,但这将导致无法一次全部激活它们.因此,基本上我认为我需要的不是快速失败"的Promises.all()版本.

执行此操作的正确方法是什么?

解决方案

要严格使用ES6 Promise,您将需要将每个Promise封装在另一个包装Promise中,当包装的Promise被实现或被拒绝时,该包装将得到解决./p>

您可以这样做:

Promise.all( 
  promises.map( promise => Promise.resolve( promise ).catch( _=>_ ) )
).then ( function ( ) {
    // All promises finished
} );

这假定promises是一个Promise和/或值的数组.

I'm writing Javascript which needs these events to happen in this order:

  1. Fire off several API calls simultaneously
  2. Once all calls have completed and responses have returned, execute a line of code

Sounds simple but the tricky part is that I can't use Promises.all() because I still want that line of code to execute after all promises have been fulfilled, successful or not. Unless I misunderstand Promises.all(), one failing would cause the line of code to not execute in then() and execute too soon in error().

I very well might be missing something obvious but the only other way I can see would be to chain the API call promises together but that would result in not firing them all at once. So basically I think I need a version of Promises.all() that isn't "fail-fast".

What's the proper way to do this?

解决方案

To do it strictly using ES6 promises, you will need to wrap each promise in another wrapper promise, which gets resolved when the wrapped promise is fulfilled or rejected.

You can do that like this:

Promise.all( 
  promises.map( promise => Promise.resolve( promise ).catch( _=>_ ) )
).then ( function ( ) {
    // All promises finished
} );

This assumes that promises is an array of promises and/or values.

这篇关于ES6 Promises/在实现多个Promise后调用函数(不能使用Promises.all)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 09:34