promise--save you from callback
最近开了新项目,后端使用HAPI,前端是react-native做app,我的任务就是构建后端系统提供api给前端调用。hapi的功能很强大,毕竟是专门提供api的框架,与express各有千秋。
之前的一个项目以为比较古老,用的都是callback函数,之前我添加新功能的时候,回调写的欲仙欲死。这次决定能用promise的地方统统使用promise。
首先我考虑了bluebird这个包,在github上人气也很高,封装了各种promise的功能。去官网看了一下简单的介绍,使用很简单。bluebird还提供了promisifyAll这个方法将非promise的方法转换成支持promise的方法。我在一个路由函数中使用了下,部分代码简单写一下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| const Promise = require('bluebird'), _label = Promise.promisifyAll(require('../service/label.service')) const insertlabel = (req, reply) => { const msg = new message(), label = req.payload.label, store_id = req.payload.store_id; _label.insert(label, store_id) .then(()=>{ reply(msg.success('success')); }) .catch((err)=>{ console.error(err); }) };
|
insert是label.service.js中的方法,但是并不是promise方法,函数返回的其实是一个callback。promisifyAll将promise化了。
之后我有尝试了原生的promise,即直接将insert这个方法使用promise改写。改写前的insert方法如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| insert (label, store_id, callback) { const model = new label_mongo({ store_id: objectid(store_id), label: label }); model.save((err) => { if (err) { console.log('ERROR: insert new data fail') return callback(false) } else { return callback(true) } }); },
|
改写后
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| insert (label, store_id) { const model = new label_mongo({ store_id: objectid(store_id), label: label }); return new Promise((resolve, reject)=>{ model.save((err) => { if (err) { reject('ERROR: insert new data fail') } else { resolve(); } }); }) }
|
这样同样可以在路由函数中使用promise方法调用then()等api。再也不用担心陷入回调地狱中。
实际使用中建议还是使用bluebird、q这样的promise包,毕竟人家已经帮你把一些坑都填好了,直接用就是,当然,如果你开发周期不紧,有时间开发这样的功能插件的化,开发一个属于自己的promise包还是很有好处的。^o^
谢谢观看。