BluebirdJS:请并行运行的函数 [英] BluebirdJS: Make a function run in parallel

查看:217
本文介绍了BluebirdJS:请并行运行的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是比较新的Javascript中的承诺,但最近爱上了自己的风采,尤其是在蓝鸟库。

I'm relatively new to Promises in Javascript, but have recently fell in love with their elegance, particularly in the Bluebird library.

这可能是一个新手的问​​题,但我怎么能转换成正常同步功能异步运行?如果我举个例子,要计算的Math.random()*范围三十次平行,我究竟是如何能做到这一点与承诺(无论Q或蓝鸟) ?

This is probably a newbie question, but how could I convert a normally-synchronous function to run asynchronously? If I, for example, wanted to compute Math.random()*RANGE thirty times in-parallel, how exactly could I do that with promises (in either Q or Bluebird)?

推荐答案

首先,承诺不会帮你做code并行运行。他们是运行时,你的任务完成等code或协调与其他任务这个任务的工具。但是,让你的当前code运行与其他code平行无关与承诺。

First off, promises won't help you make code run in parallel. They are a tool for running other code when your task is done or coordinating this task with other tasks. But making your current code run in parallel with other code has nothing to do with promises.

第二关,有一点好处(以及很多并发症)采取同步任务,并试图使其工作更像是一个异步任务,除非它是如此长时间运行,它与其他操作的响应干扰。计算一组随机数不太可能是该长正在运行的任务。

Second off, there's little advantage (and a lot of complication) to taking a synchronous task and trying to make it work more like an asynchronous tasks unless it is so long running that it interferes with the responsiveness of other operations. Computing a set of random numbers is unlikely to be that long a running task.

如果你真的想在浏览器并行执行,你会去使用WebWorkers这是创建基于浏览器的JavaScript的一个真正独立的执行线程的唯一途径。比WebWorkers其他的JavaScript在浏览器是单线程的,所以没有并行执行。有可能将在其与其他事物在浏览器怎么回事,可以交织您code执行连续的setTimeout()调用执行code的小块允许其他浏览器的任务,另一个运行长时间运行的任务保持响应。

If you truly want parallel execution in a browser, you would have go use WebWorkers which is the only way to create an truly independent execution thread in browser-based javascript. Other than WebWorkers, javascript in a browser is single threaded so there is no parallel execution. It is possible to execute small chunks of code on successive setTimeout() calls which will interweave your code execution with other things going on in the browser and can allow other browser tasks to remain responsive while running another long running task.

您可以看到使用处理大型阵列中的数据块的例子的setTimeout()此处<一个href=\"http://stackoverflow.com/questions/10344498/best-way-to-iterate-over-an-array-without-blocking-the-ui/10344560#10344560\">Best方法来遍历数组,而不会阻塞UI 以允许其他事情的处理块之间运行英寸承诺可以被添加到这样的事情作为管理任务的完成或管理与其他工作的协调的方法,但承诺没有真正帮助您充分利用它的块工作。

You can see an example of processing a large array in chunks using setTimeout() here Best way to iterate over an array without blocking the UI to allow other things to run in between chunks of processing. Promises could be added to something like this as a method of managing the completion of the task or managing its coordination with other tasks, but promises don't actually help you make it work in chunks.

这篇关于BluebirdJS:请并行运行的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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