node.js - 在 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');
});
解决方案
你可以试试这个....我认为这应该工作
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));
推荐阅读
- django - POST 正文未与 APIClient DRF 一起发送
- javascript - 原生结帐 WooCommerce - AJAX 问题
- salesforce - jsforce metadata.deploy,部署ID
- android - 将 RealmObject 与 Recyclerview ListAdapter 一起使用
- asynchronous - 尝试根据响应其他 API 来响应 Slack
- linux - 按所有者在目录中汇总文件大小的最快方法
- xml - XQuery 按不同类别显示 TITLE 顺序 ORDER BY 年份
- java - 将多个参数传递给 web.xml 中的 org.apache.cxf.jaxrs.swagger.Swagger2Feature
- linux - Ubuntu 18 上的 nginx 网站未在公共 IP 上加载
- php - 如何制作简单的模板?