如何串行或者并行运行异步循环?

在使用循环处理异步的魔法之前,我们先来看下我们是怎么处理同步循环的。

同步循环

很久以前我写的循环是这样的:

for (var i = 0; i < array.length; i++) {
var item = array[i];
// do something with item
}

后来 JavaScript 提供了很多新的特性,现在我们会更倾向于用下面这种写法:

array.forEach((item) => {
// do something with item
})

在开发过程可能会有这么一种需求,我们需要在循环中异步处理 item,那么可以怎么做呢?

异步循环

如何在循环中使用 await?我们试着写一个异步函数,然后 await 每一次循环任务。

async function processArray(array) {
array.forEach(() => {
// define synchronous anonymous function
// it will throw error here
await func(item)
});
}

这个代码会抛出一个错误,因为我们不能在同步方法中使用 await, processArray 确实是异步函数,但是 array.forEach 里的匿名函数是同步的。

1. 不要等待结果

要处理这个问题,我们可以把这个匿名函数定义为异步的:

async function processArray(array) {
array.forEach(() => {
await delayedLog(item)
});
console.log('Done!');
}

但是这样的话 forEach 方法就相当于异步的了,不会等待遍历完所有的 item,例如下面这段代码:

function delay () {
return new Promise(resolve => setTimeout(resolve, 300));
} async function delayedLog(item) {
// notice that we can await a function that returns promise
await delay();
// log item only after a delay
console.log(item);
} async function processArray(array) {
array.forEach(() => {
await delayedLog(item)
});
console.log('Done!');
} processArray([1, 2, 3]);

将会输出:

Done!
1
2
3

如果你不需要等待这个循环完成,这样就已经可以了。但是大部分情况我们还是需要等待这个循环完成才进行之后的操作。

2. 串行遍历

要等待所有的结果返回,我们还是要回到老式的 for 循环写法:

async function processArray(array) {
for (const item of arr) {
await delayedLog(item);
}
console.log('Done!');
}

最后的结果符合我们的预期:

1
2
3
Done!

上面这段的遍历代码是串行执行的,我们也可以把它换成并行的。

3. 并行遍历

我们可以稍微更改上面的代码来编程并行的:

async function processArray(array) {
// map() 方法创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。
// async 修饰的方法返回值是一个promise对象,因此下面map的返回值就是一个promise列表
const promiseArr = array.map(delayedLog);
// wait until all promises are resolved
await Promise.all(promiseArr);
console.log('Done!');
}

(注意:对于特别大的数组不建议使用这种写法,太多的并行任务会加重 CPU 和内存的负荷)

转自:https://zhuanlan.zhihu.com/p/31000936

node Later定时任务的更多相关文章

  1. node编写定时任务,for循环只执行一遍的解决办法

    在用node编写定时任务时候,发现for循环只执行i=0这一次,就不接着循环执行了,下面贴上代码: exports.task = async function(ctx){ let { app } = ...

  2. node.js定时任务 node-schedule

    先安装 node-schedule npm install node-schedule //1:确定时间 //例如:2014年2月14日,15:40执行 var schedule = require( ...

  3. node.js定时任务:node-schedule的使用

    安装 npm install node-schedule 使用方法 1:确定时间 例如:2014年2月14日,15:40执行 var schedule = require("node-sch ...

  4. babeljs源码

    babel.min.js!function(e,t){"object"==typeof exports&&"object"==typeof mo ...

  5. node定时任务——node-schedule模块使用说明

    在实际开发项目中,会遇到很多定时任务的工作.比如:定时导出某些数据.定时发送消息或邮件给用户.定时备份什么类型的文件等等. 一般可以写个定时器,来完成相应的需求,在node.js中自已实现也非常容易, ...

  6. PHP定时任务实现(计划任务 vs node.js)

    PHP自动任务(单线程) 一.计划任务实现 :最终需要在服务器(windows)上 设置计划任务 1.写好php任务文件 auto.php:链接数据库 判断条件操作数据库 2.创建bat文件 例:ru ...

  7. 【重学Node.js 第4篇】实现一个简易爬虫&启动定时任务

    实现一个简易爬虫&启动定时任务 课程介绍看这里:https://www.cnblogs.com/zhangran/p/11963616.html 项目github地址:https://gith ...

  8. node.js中使用node-schedule实现定时任务

    摘要:有时我们需要在每天的固定时间执行某个脚本,或者在某个固定时间执行某个任务.NodeJS中的 node-schedule 可以很好的实现定时任务. 1.安装 npm install node-sc ...

  9. node中的定时任务

    node-schedule每次都是通过新建一个scheduleJob对象来执行具体方法. 时间数值按下表表示 * * * * * * ┬ ┬ ┬ ┬ ┬ ┬ │ │ │ │ │ | │ │ │ │ │ ...

随机推荐

  1. 后台返回json数据,前台显示代码

    List list = "从DAL获取的数据集合" //取出分页标签html int pageIndex = context.Request["pageIndex&quo ...

  2. poj.1094.Sorting It All Out(topo)

    Sorting It All Out Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 28762   Accepted: 99 ...

  3. 交叉编译php5,、nginx、squid方法

    本文为原创,转载请注明:http://www.cnblogs.com/tolimit/ 交叉编译php5 软件版本:php-5.4.27 依赖库:zlib,libxml2 交叉编译器:arm-hisi ...

  4. 用LoadRunner实现接口测试

    接口测试的两种方法 其实无论用那种测试方法,接口测试的原理是通过测试程序模拟客户端向服务器发送请求报文,服务器接收请求报文后对相应的报文做出处理然后再把应答报文发送给客户端,客户端接收应答报文这一个过 ...

  5. loadrunner跑场景的时候出现:Abnormal termination, caused by mdrv process termination

    1.问题 loadrunner跑场景的时候出现:Abnormal termination, caused by mdrv process termination. 备注:我使用的是RTE协议录制的脚本 ...

  6. Android四大组件之Service

    Android四大组件之Service Android支持服务的概念,服务是在后台运行的组件,没有用户界面,Android服务可用有与活动独立的生命周期.Android支持两种类型的服务: 本地服务: ...

  7. Linux大神必备-文本编辑器

    导读 我们在 Linux 上不缺乏非常现代化的编辑软件,但是它们都是基于 GUI(图形界面)的编辑软件.正如你所了解的:Linux 真正的魅力在于命令行,当你正在用命令行工作时,你就需要一个可以在控制 ...

  8. 【OpenStack】OpenStack系列17之OpenStack私有云设计一

    [软件系统] 1.操作系统(Minimal最小化安装): CentOS-6.6-x86_64,CentOS 6最后一个版本,官方建议版本. 相对于6.5版本: 强化对 SCSI 设备的处理,有助应付某 ...

  9. maven3 junit4 spring3 jdk8 :junit一直报错,害的我几个星期都是这个错,你妹的!

    [org.springframework.test.context.junit4.SpringJUnit4ClassRunner]SpringJUnit4ClassRunner constructor ...

  10. Java for LeetCode 030 Substring with Concatenation of All Words【HARD】

    You are given a string, s, and a list of words, words, that are all of the same length. Find all sta ...