其他分享
首页 > 其他分享> > 用ES6写的获取最近一天工作日

用ES6写的获取最近一天工作日

作者:互联网

通过'http://tool.bitefu.net/jiari/?d=20210815获取最近一天工作日,此API反回0表示工作日,1表示周末,2表示假期

//workday.js

import fetch from 'node-fetch'

const URL = 'http://tool.bitefu.net/jiari/?d=' // 日期格式  d=20210814

const fetchAsync = async (url, date) => {
  const response = await fetch(url + date)
  return await response.text()
}

function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms))
}

async function getLastWorkday(datetime = new Date()) {
  let lastWorkday
  while (true) {
    let day = (lastWorkday && datetime.getDate() - 1) || datetime.getDate()
    lastWorkday = new Date(datetime.setDate(day))
      .toISOString()
      .split('T')[0]
      .split('-')
      .join('')
    const isWorkDay = await fetchAsync(URL, lastWorkday)
    if (isWorkDay === '0') {
      break
    }
    await sleep(2000)
  }

  return [lastWorkday, datetime]
}

用法

import getLastWorkday from './workday.js'

const lastWorkday = async () => {
  let result = await getLastWorkday()
  console.log(result)
  return result
}

lastWorkday()

标签:ES6,const,await,datetime,获取,result,return,lastWorkday,工作日
来源: https://www.cnblogs.com/joe62/p/15142774.html