node.js中promise的一个使用小例子
今天做一个项目,展现一个页面需要从服务器请求两次数据,太繁琐了,今天用promise规范了一下,只需要从服务器发送一次数据即可实现。
需要发送的数据:
和
我在controller中写了如下代码:
OrderForm = require('../models/OrderForm.js'); Person = require('../models/Person.js'); function OrderForm(){ } OrderForm.save = function(req,res){ OrderForm.save(req.body.name,req.body.restaurant,req.body.meal,req.body.price) }; var get_person = new Promise(function(resolve,reject){ Person.getAll() .then(function(name){ console.log(name) resolve(name) }) }); var get_order_list = new Promise(function(resolve,reject){ OrderForm.statics.getAll() .then(function(list){ console.log(list) resolve(list) }) }); OrderForm.getAll = function(req,res){ Promise.all([get_person,get_order_list]).then(function(result){res.send(result)}); }; module.exports = OrderForm;
需要说一下的是最后的result存入了之前promise中resolve的信息,打印出来是这个样子的:
可以看到放到了一个数组里,取的时候:
function show_order_list() { $.when($.ajax({ url:"get_meal_list", type:"GET", dataType:"json", success:function(data){ var meal_list = []; var name_list = []; data[1].forEach(function(list) { meal_list.push(list); var meal = {name: list.list, restaurant: list.restaurant, meal: list.meal, price: list.price}; localStorage.setItem('meal_list', JSON.stringify(meal_list)); }); data[0].forEach(function (name) { if (name_list.indexOf(name.list) == -1) { name_list.push(name.list); localStorage.removeItem('all_people_list'); localStorage.setItem('all_people_list', JSON.stringify(name_list)); } }) } })).then(function(){show_lists()}); }
分别用[0]和[1]就ok了
相关推荐
nmgxzm00 2020-11-10
xixixi 2020-11-11
88254251 2020-11-01
MarukoMa 2020-09-02
88234852 2020-09-15
陈旭阳 2020-08-31
whynotgonow 2020-08-19
前端开发Kingcean 2020-07-30
whynotgonow 2020-07-29
bowean 2020-07-08
前端开发Kingcean 2020-07-08
88520191 2020-07-05
前端开发Kingcean 2020-06-27
88481456 2020-06-18
whynotgonow 2020-06-16
88520191 2020-06-13
88520191 2020-06-13
89500297 2020-06-13