根据给定变量的长度动态创建函数

时间:2019-01-23 11:48:27

标签: javascript

我有一个在其他JS库中定义的函数调用“ getDocID”,我们可以为此传递一个回调函数myCallback。

要获得一个以上的ID,我们必须将其链接起来,我们需要像下面这样调用函数,效果很好。

#define HSRX_DMA_BUFFER_SIZE    PAGE_SIZE

struct hsrx_dmarx_data *dmarx = &hsrx_local->dmarx;
struct dma_chan *rxchan = dmarx->chan;
struct hsrx_sgbuf *sgbuf = &hsrx_local->dmarx.sgbuf_a;
struct dma_slave_config rx_conf = {
    .src_addr = (dma_addr_t)hsrx_local->phy_rx_addr,
    .src_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES,
    .direction = DMA_DEV_TO_MEM,
    .src_maxburst = 32,
    .device_fc = false,
};

dma_addr_t dma_addr;
sg->buf = dma_alloc_coherent(chan->device->dev,
        HSRX_DMA_BUFFER_SIZE, &dma_addr, GFP_KERNEL);

rxdesc = dmaengine_prep_slave_sg(rxchan, &sgbuf->sg, 1,
        DMA_DEV_TO_MEM,
        DMA_PREP_INTERRUPT | DMA_CTRL_ACK);

if (!rxdesc) {
    goto err_busy;
}
rxdesc->callback = hsrx_dma_callback;
rxdesc->callback_param = hsrx_local;

dmarx->cookie = dmaengine_submit(rxdesc);
if (dma_submit_error(dmarx->cookie)) {
    dev_err(hsrx_local->dev, "DMA submit failed\n");
    goto err_submit;
}

dma_async_issue_pending(rxchan);

任何人都可以指导我优化上述代码并根据testValues的长度动态创建函数。

1 个答案:

答案 0 :(得分:1)

使用Array#forEach并进行范围界定。

function getDocID(id, num, callback){
   callback({ID:`optId: ${id} and testVal: ${num}`});
}

function setDocIds() {
  const testValues = ["2980", "2981", '2982'];
  const optID = "someValue";
  testValues.forEach((n, i) => {
    getDocID(optID, n, function(result) {
      const appID = result.ID;
      const id = i === 0 ? "emailtemplate" : `div_${i}`;
      document.getElementById(id).innerHTML = appID;
    });
  });
}

setDocIds();
<div id="emailtemplate"></div>
<div id="div_1"></div>
<div id="div_2"></div>