NodeJs - 等待来自异步方法的promise解析。

时间:2015-08-08 17:44:01

标签: javascript node.js asynchronous bluebird

我已经编写了一个验证库,我希望能够在Node中同步和异步调用。我尝试过使用async / co的promises但是我 无法到达任何地方。有没有人对如何使这段代码同步有一个很好的建议?我试图从验证工厂调用它,返回的查找与数据库异步。

var lookupFactory = require('../lookup/lookupFactory');
var Promise = require("bluebird");
var async = require('async');

exports.validate = function (required, field, errors) {
    if (required && field.value == null) {
        errors.push('Field is required');
       return;
   }

    var lookupType = field.validation.lookupType;
    var s = lookupFactory.lookup(lookupType);
    s.validate('12', function (err, data) {
        if (data.length != 1) {
            errors.push('Field value is not valid');
        }
    });
};

2 个答案:

答案 0 :(得分:0)

我喜欢promisses。

exports.validate = function (required, field, errors) {
    return new Promise(function(fulfill) {
        if (required && field.value == null) {
            errors.push('Field is required');
            return;
        }

        var lookupType = field.validation.lookupType;
        var s = lookupFactory.lookup(lookupType);
        s.validate('12', function (err, data) {
            if (data.length != 1) {
                errors.push('Field value is not valid');
            }
            fulfill(null /*Argument passed to the other function*/); //Is it here the code end?
        });
    });
}

答案 1 :(得分:0)

exports.validate = function (required, field) {
  var lookupType = field.validation.lookupType;
  var s = lookupFactory.lookup(lookupType);

  return new Promise(function(resolve, reject) {
    if (required && field.value == null) {
      return reject('Field is required');
    }

    s.validate('12', function (err, data) {
      if(err) {
        return reject(err);
      } else if (data.length != 1) {
        return reject('Field value is not valid');
      }

      resolve(data);
    });
  });
}

使用示例:

validate(true, 'name')
  .then(function(data) { console.log('Validation succeeded:', data); },
        function(reason) { console.log('Validation failed:', reason); });