最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

如何为npm软件包脚本实现连续循环

运维笔记admin18浏览0评论

如何为npm软件包脚本实现连续循环

如何为npm软件包脚本实现连续循环

我的代码是

我的index.js脚本如下:

import personfaces from './dist/index';

const dnte = new personfaces();

dnte.getImage({ width: 256, height: 256, type: 'file' })
.then(res => { console.log('result->', res); })
.catch(err => { console.log('error->', err); });

我使用终端命令“ npm start”运行代码,但我想将其作为连续的重复循环,例如运行100次。每次我在终端上运行代码时,它都会下载一个图像,并且希望它是具有100次运行的连续过程,以便生成100张图像。

有没有一种方法可以运行终端命令100次运行或将100次运行添加到我的主代码中。

回答如下:

是的,可以,但是就此而言,您不需要它。您必须运行函数一百次。否则,您可以创建一个bash文件并根据您的操作系统运行它,并每次运行‍ npm start代码。作业或OS中的时间表。

但是最简单的方法是使用递归函数。

import personfaces from './dist/index';

const dnte = new personfaces();

var count = 100
recursiveFun(0);
function recursiveFun(index) {
  if (index === count)
    return;
  dnte.getImage({ width: 256, height: 256, type: 'file' })
    .then(res => {
      console.log('result->', res);
      recursiveFun(index + 1)
    })
    .catch(err => {
      console.log('error->', err);
      recursiveFun(index)
    });
}

第二种方式使用节点模块:

npm上的p-iteration模块实现了Array迭代方法,因此可以非常直接地将它们与async / await一起使用。

循环遍历数组以对每个元素执行异步操作。有时您必须执行asynchronous action on each elements of an array,但必须等待上一个操作完成才能继续执行下一个操作。

发布评论

评论列表(0)

  1. 暂无评论