使用Q进行同步的Promises操作
2017-11-10 20:38
260 查看
如何通过使用Q来并发执行多个promises呢?
上面的代码输出结果为1。很显然,你不能简单地将各个promises都放到一个Q()函数里来执行,这样只有第一个promise会被正确地执行,剩余的都会被忽略掉。
你可以使用Q.all来代替上面的方法,它们之间的主要区别是前者将每个promise单独作为参数进行传递,而Q.all则接收一个数组,所有要并行处理的promise都放到数组中,而数组被作为一个独立的参数传入。
上面的代码输出结果为[1, 2, 3]。所有的promises都被正确执行,但是你发现Q.all返回的结果依然是一个数组。我们也可以通过下面这种方式来获取promises的返回值:
除此之外,我们还可以将then替换成spread,让Q返回一个个独立的值而非数组。和返回数组结果的方式相同,这种方式返回结果的顺序和传入的数组中的promise的顺序也是一致的。
那如果其中的一个或多个promsie执行失败,被rejected或者throw error,我们如何处理错误呢?
如果传入的promises中有一个被rejected了,它会立即返回一个rejected,而其它未完成的promises不会再继续执行。如果你想等待所有的promises都执行完后再确定返回结果,你应当使用allSettled:
Q(Q(1), Q(2), Q(3)) .then(function (one, two, three) { console.log(one); console.log(two); console.log(three); }, function (ex) { console.error(ex.stack); }); // 1
上面的代码输出结果为1。很显然,你不能简单地将各个promises都放到一个Q()函数里来执行,这样只有第一个promise会被正确地执行,剩余的都会被忽略掉。
你可以使用Q.all来代替上面的方法,它们之间的主要区别是前者将每个promise单独作为参数进行传递,而Q.all则接收一个数组,所有要并行处理的promise都放到数组中,而数组被作为一个独立的参数传入。
Q.all([Q(1), Q(2), Q(3)]) .then(function (one, two, three) { console.log(one); console.log(two); console.log(three); }, function (ex) { console.error(ex.stack); }); // [1,2,3]
上面的代码输出结果为[1, 2, 3]。所有的promises都被正确执行,但是你发现Q.all返回的结果依然是一个数组。我们也可以通过下面这种方式来获取promises的返回值:
Q.all([Q(1), Q(2), Q(3)]) .then(function (one, two, three) { console.log(one[0]); console.log(one[1]); console.log(one[2]); }, function (ex) { console.error(ex.stack); }); // 1 // 2 // 3
除此之外,我们还可以将then替换成spread,让Q返回一个个独立的值而非数组。和返回数组结果的方式相同,这种方式返回结果的顺序和传入的数组中的promise的顺序也是一致的。
Q.all([Q(1), Q(2), Q(3)]) .spread(function (one, two, three) { console.log(one); console.log(two); console.log(three); }, function (ex) { console.error(ex.stack); }); // 1 // 2 // 3
那如果其中的一个或多个promsie执行失败,被rejected或者throw error,我们如何处理错误呢?
Q.all([Q(1), Q.reject('rejected!'), Q.reject('fail!')]) .spread(function (one, two, three) { console.log(one); console.log(two); console.log(three); }, function (reason, otherReason) { console.log(reason); console.log(otherReason); }); // rejected! // undefined
如果传入的promises中有一个被rejected了,它会立即返回一个rejected,而其它未完成的promises不会再继续执行。如果你想等待所有的promises都执行完后再确定返回结果,你应当使用allSettled:
Q.allSettled([Q(1), Q.reject('rejected!'), Q.reject('fail!')]) .then(function (results) { results.forEach(function (result) { if (result.state === "fulfilled") { console.log(result.value); } else { console.log(result.reason); } }); }); // 1 // rejected! // fail!
相关文章推荐
- 关于Jpa使用Update方法进行更新操作,却没有同步到数据库的原因
- 使用node.js中的async模块进行数据库的同步操作
- nodejs中使用async来对异步操作进行同步,避免多个异步同时启动引发连接错误
- java并发编程使用锁进行数据同步操作一
- 在eclipse中使用github进行代码的同步操作
- 如何使用ASP进行打印操作
- 如何使用ANT自动进行数据库的相关操作
- 使用Log4j进行日志操作
- 使用程序对Office自动化进行操作的一些文章。
- 单独使用MFC CRecord类进行数据库操作(原创心得)
- [How To]如何使用Wildfish进行ISeries开发---多操作篇
- VC中使用ADO进行数据库操作
- 在Delphi中使用CreateOleObject方法对WORD文件进行操作
- 使用IOCP进行客户socket与完成端口关联操作
- 如何使用ANT自动进行数据库的相关操作
- 使用xmltextreader对xml进行简单的读取和写入操作
- 使用 ShellExecute 来进行 Ping 操作!
- 使用存储过程进行数据库操作
- 使用Log4j进行日志操作
- servlet学习笔记(3)-使用Java Servlet API 进行会话管理(对session的操作)