首页 > 解决方案 > 在 Promise 中调用函数

问题描述

来自另一种主要语言,我不完全确定 Promises 的 resolve() 性质如何工作,因此这个问题的基本性质。

我的目标是在屏幕上显示一个下拉列表(选择)元素。我在获取数据并将其发送到模板进行渲染时没有困难。困难在于我需要遍历记录并将它们构建成 HTML 字符串以支持我们需要的显示。在将它们构建成字符串之前,我需要在每个模板的文本上运行一个函数,它将用数据库中的值替换一些代码。

在顺序代码中,骨架代码可能如下所示:

template_recs = get_template_recs(user_id)

for each template_rec

  template_text = template_rec.text

  template_text_new = replace_codes(template_text, user_id)

  template_text_new_html = (html_start + template_text_new + html_end)

  template_options_html = (template_options_html + template_text_new_html)

next

display template_options_html

当然,我想以异步方式开发它,其中 html 在替换代码后包裹在 template_text 周围,并且在所有记录都添加到 html 变量后显示整个 html。

我写了下面的代码,但它不起作用。在我深入纠正它之前,我的问题是这是否是解决这个问题的最佳方法。我什至走在正确的轨道上吗?

我正在努力将一个大型框架从同步代码转移到 nodejs,我想确保我从一开始就做对了。


  let get_tt_recs = function() {

    return new Promise(function (resolve, reject) {

      tt_recs = tt.get(req.user, ind_id, cus_id);

      if (tt_recs) {
        resolve(tt_recs);
      } else {
        reject();
      }

    });

  };

  get_tt_recs.then(function (tt_recs) {

    tt_rec_div = function() {

      return new Promise(function (resolve, reject) {

        tt_recs = sms.tt_recs_format(tt_recs);

        if (tt_recs) {
          resolve(tt_recs);
        } else {
          reject();
        }

      });

    };

  }).then(function () {

    complete();

  }).catch(function () {

    console.log('get_tt_recs() did not return any tt_recs');

  });

标签: node.jses6-promise

解决方案


你可以试试这个....我认为这应该工作

 let get_tt_recs = function() {

    return new Promise(function (resolve, reject) {

      tt_recs = tt.get(req.user, ind_id, cus_id);
      if(tt_recs !==null) sms_recs = sms.tt_recs_format(tt_recs);

      if (tt_recs && sms_recs ) {
        resolve({tt_recs,sms_recs})

      } else {
        reject();
      }

    });

  };


  get_tt_recs().then(data=> console.log(data)).catch(e =>console.log(e));

推荐阅读