异步replace,replace异步处理数据

不多说,上代码,不过这段代码最终结果是Promise,需要拿到数据以后进行promise处理。

import { getBySPZCode } from '@/api/genealogy/people'    //封装的接口请求


export const XianShiSPZ = async (value: any) => {
  let str: any = value || ''    //数据是否为空
  const pattern = /{SPZ(\d*)}/g    //正则

  if (str.indexOf('{SPZ') != -1) {    //是否找到数据
    str = await replaceAsync(str, pattern, myAsyncFn)     //找到了执行
  }

  return str
}

async function myAsyncFn(match, data) {
  const fetchedJson = await getBySPZCode('SPZ' + data)    // 接口请求数据

  //最终返回结果
  return `<img style="width: 16px;display: inline-block;" src="${fetchedJson}" alt="">`   
}

async function replaceAsync(str, regex, asyncFn) {
  const promises: any = []    //存入数据
  str.replace(regex, (match, ...args) => {
    const promise = asyncFn(match, ...args)    //第一次执行replace操作,找到所有需要替换的数据
    promises.push(promise)    //存入到数组
  })

  //所有的promise执行完毕以后通过all拿到值
  const data = await Promise.all(promises)   

  // data.shift() 每次执行都会拿到data数组第一个值返回,类似于splice(0,1)
  return str.replace(regex, () => data.shift())    
}

使用:

// 1.导入该方法
import { XianShiSPZ } from '@/utils/zouWuSPZ'

// 2.我这里是通过async await,具体使用什么看你们自己
let a = ref()
const fun = () => {
    a.value = await XianShiSPZ('1252{SPZ00001}5121{SPZ00003}')
}
fun()

我们公司这个替换主要是为了替换接口拿到的显示数据,所以拿到数据以后做替换处理在显示,这是我自己写的一个数组和对象的替换方式,仅供参考:

//数据也可以是对象,这里就用一个数组,对象跟数组是一样的
let arr = [
    {
        a: null,
        b: undefined,
        c: '1',
    },
    {
        a: null,
        b: 2,
        c: undefined,
    },
    {
        a: 3,
        b: null,
        c: undefined,
    },
]

async function chuliObject(obj) {
    // 传入参数不是对象
    if (typeof obj !== 'object' || obj === null) {
        return obj
    }

    let newArr = {} //最终返回值
    let arr = [] //存放值不为空的键

    // 当前是数组
    if (Object.prototype.toString.call(obj) == '[object Array]') {
        // 存在数组的话,把返回值改为数据,循环遍历数据,在通过递归方式返回数据
        newArr = []
        await obj.forEach(async (Objitem) => {
            //注意,这里是一个异步!!!!
            newArr.push(chuliObject(Objitem))
        })
        return await Promise.all(newArr)
    }

    Object.keys(obj).forEach(async (item) => {
        if (
            obj[item] == null ||
            obj[item] == undefined ||
            obj[item] == '' ||
            typeof obj[item] == 'number'
        ) {
            newArr[item] = obj[item]
        } else {
            arr.push(item) //存放有数据的键
        }
    })
    for (const key of arr) {
        // 这里配合上面的XianShiSPZ方法使用
        newArr[key] = await XianShiSPZ(obj[key])
    }
    return newArr
}

console.log(chuliObject(arr))    //嗯,这里要注意,返回的是promise,需要做一下处理

附上这个demo的全体代码,这个是我们公司自己的,借鉴一下就好了:

import { getBySPZCode } from '@/api/genealogy/people'    //接口

// 数据处理
export async function chuliObject(obj) {
  // 传入参数不是对象
  if (typeof obj !== 'object' || obj === null) {
    return obj
  }

  let newArr: any = {} //最终返回值
  const arr: any = [] //存放值不为空的键

  // 当前是数组
  if (Object.prototype.toString.call(obj) == '[object Array]') {
    // 存在数组的话,把返回值改为数据,循环遍历数据,在通过递归方式返回数据
    newArr = []
    await obj.forEach(async (Objitem) => {
      //注意,这里是一个异步!!!!
      newArr.push(chuliObject(Objitem))
    })

    return await Promise.all(newArr)
  }

  Object.keys(obj).forEach(async (item) => {
    if (
      obj[item] == null ||
      obj[item] == undefined ||
      obj[item] == '' ||
      typeof obj[item] == 'number'
    ) {
      newArr[item] = obj[item]
    } else {
      arr.push(item) //存放有数据的键
    }
  })
  for (const key of arr) {
    newArr[key] = await XianShiSPZ(obj[key])
  }

  return newArr
}

// 第一部操作
const XianShiSPZ = async (value: any) => {
  let str: any = value || ''
  const pattern = /{SPZ(\d*)}/g

  if (str.indexOf('{SPZ') != -1) {
    str = await replaceAsync(str, pattern, myAsyncFn)
  }

  return str
}

// 接口请求数据
async function myAsyncFn(match, data) {
  // match is an url for example.
  console.log(match, data)

  const fetchedJson = await getBySPZCode('SPZ' + data)

  return `<img style="width: 16px;display: inline-block;" src="${fetchedJson}" alt="">`
}

// 双重replace替换
async function replaceAsync(str, regex, asyncFn) {
  const promises: any = []
  str.replace(regex, (match, ...args) => {
    const promise = asyncFn(match, ...args)
    promises.push(promise)
  })
  const data = await Promise.all(promises)
  return str.replace(regex, () => data.shift())
}

猜你喜欢

转载自blog.csdn.net/weixin_50587417/article/details/134928454
今日推荐