重写 JS 回调以使用 promises

问题描述 投票:0回答:1

最近刚接触到JS的promises,所以想重写很多回调来使用promises。查看示例似乎非常直接和容易,直到我必须自己调整它。

我有下面的例子,我想重写以使用承诺。

getData = function (id, key, required, callback) {
  // do a lot of things
  let lParams = {
    tParams: { start: 0, Query: numQueries },
    callback: () =>  {
      if (!required)
        showGrid(id);
      if (callback)
        callback();
    }
  };
  //do some work...
  e = some condition
  if(e)
    e.load(tParams);
  else { 
    e.read(new data.Operation(tParams), tParams.callback);
  }

----------------函数使用示例--------

甚至可以从另一个 js 文件中使用

report.execute = function (params) {
      // Do a lot of things...
      showMessage("Working on data ...");
      getData(curFormID, data.key, false
        , function () {
          workStat = 1;
          ppl.pageReady();
        });
    }
  });
};

---------------- 到目前为止,我尝试重写以使用 promises ----------------

getData = async (isoForm, nKey, onlyGet) => {
  
  let promise = new Promise((resolve, reject) => {
     // do the things that are in the getData function above???
  })
}

我如何将它与

report.execute(...)
联系起来 提前致谢

javascript promise callback
1个回答
-4
投票

我使用 chatGPT 来尝试解决您的问题,这就是答案:

function getData(id, key, required) {
  return new Promise(function(resolve, reject) {
    // do a lot of things

    let lParams = {
      tParams: { start: 0, Query: numQueries },
      callback: () => {
        if (!required) {
          showGrid(id);
        }
        resolve();
      },
    };

    // handle errors
    try {
      // do some work
    } catch (error) {
      reject(error);
    }
  });
}

© www.soinside.com 2019 - 2024. All rights reserved.