Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.3k views
in Technique[技术] by (71.8m points)

一个js问题。

一个数组中假设格式是

const data = [{
    name: 'a',
    ref: ['b', 'c']
}, {
    name: 'b',
    ref: ['d']
}, {
    name: 'c',
    ref: ['d']
}, {
    name: 'd',
    ref: null
}, {
    name: 'e',
    ref: ['f']
}, {
    name: 'f',
    ref: null
}]

上面那个绑定表单的情况下,

form: {
    a: '',
    b: '',
    c: '',
    d: ''
}

说明: 需要遍历数组然后判断是否有ref 如果有ref就把调用接口
拿a来说 接口数据传递 { b: xx, c: xx},返回的数据赋值给this.form.a = res.data. 但是ref中的 b , c也有依赖的话 就需要先获取b,c的值,最后才调用接口传递赋值a.
所以就是先调用接口获取b的数据, 请求参数 {d: this.form.b} 返回内容 this.form.b = res.data
然后调用接口获取c的数据, 接口请求参数 {d: this.form.d} 返回内容 this.form.c = res.data.
获取到bc的数据后然后再才能获取a数据. 请求参数

{
    b: this.form.b,
    c: this.form.c
}

如上吧返回的数据赋值给a this.a = res.data


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

// 方便读取数据,data转成map
var dataMap = data.reduce((result, node) => {
  result[node.name] = node;
  return result;
}, {})

// 模拟接口获取数据
function getValAsync(param) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve({ val: 1, param })
    }, 500)
  })
}

// 获取接口的请求参数
async function getParam(ref) {
  const paramList = await Promise.all(ref.map(async dep => {
    const val = await getVal(dep);
    return { [dep]: val}
  }))

  return Object.assign.apply(null, paramList);
}

// 获取值
async function getVal(name) {
  const { ref } = dataMap[name];
  if(!ref) {
    return null;
  }
  const param = await getParam(ref);
  const val = await getValAsync(param);
  return val;
}

// TEST
;(async () => {
  const p = await getVal('f'); 
  console.log(p); // null
})()

;(async () => {
  const p = await getVal('e');
  console.log(JSON.stringify(p)); // {"val":1,"param":{"f":null}}
})()

;(async () => {
  const p = await getVal('a');
  console.log(JSON.stringify(p)); 
})()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...