node.js下promise的两种常见用法

最近做工程遇到一个问题:从数据库取出数据后不能有效的传到前台,用了两种解决办法callback回掉函数和promise方法,这里说一下自己对promise的理解。

promise主要用于控制函数按照自己的计划进行下去,以免造成有操作等延迟时不能得到想要的结果。

常见用法一:

var mysql = require("./db");

function Person(){

}

Person.getAll = function() {
  return new Promise(function (resolve,reject) {
    mysql.query('select*from person', function (err, rows) {
      resolve(rows);
    })
  })
};

module.exports = Person;
Person = require('../models/Person.js');
function NameController(){

}

NameController.getAll = function(req,res){
    Person.getAll()
        .then(function(list){
            res.send(list)
        })
};

module.exports = NameController;

 这是两个js文件,通过路由连接到一起,实现了由promise控制取数据。主要需要注意的是第一个函数return和resolve的内容还有第二个函数Person.getAll()的承接,括号不要落掉。

补充:可以后续链接多个.then,函数会按照顺序执行

         .catch是承接出错时的操作的。

常见用法二:Promise.all

OrderFormController.get_person_list = function(){
   return new Promise(function(resolve,reject){
        Person.getAll()
            .then(function(name){
                resolve(name);
            })
            .catch(function(error){
                console.log("get_person_list error")
            })
   });
};
OrderFormController.get_order_list = function(){
    return new Promise(function(resolve,reject){
        OrderForm.statics.getAll()
            .then(function(list){
                resolve(list);
            })
            .catch(function(error){
                console.log("get_order_list error")
            })
    });
};

OrderFormController.getAll = function(req,res){
    var get_person_list = OrderFormController.get_person_list();
    var get_order_list = OrderFormController.get_order_list();
    Promise.all([get_person_list,get_order_list])
        .then(function(order_information){
            res.send(order_information)
        });
};

这儿promise.all用于有多个promise同时完成时才能进行下一步的情况,多个函数取出的值会自动被整合到一个数组中,我的代码是整合到了order_infomation中,其中order_infomation[0]是第一个,order_infomation[1]是第二个。

node.js4.0以上版本就自带promise了,不用引用

猜你喜欢

转载自873719187.iteye.com/blog/2280397