Javascript承诺不等待(使用q,节点,咖啡)?

时间:2016-02-13 21:37:07

标签: javascript node.js coffeescript promise q

我正在尝试从mocha测试中测试我的节点模块,并且我很难理解promises应该如何工作。我无法让它等待我的承诺的解决。这是我的coffeescript代码

'use strict'
Q = require 'q'

exports.awesome = () ->
  headers = {"example" : "hello"}
  params = {"id" : "J123456789012345678"}

  console.log('response is' + JSON.stringify(@handleAPIRequest(headers,params)))
  console.log('awesome')
  'awesome'

exports.handleAPIRequest = (headers,params) ->
  @validateRequest(headers, params)
  .then(@loadFromDynamo)
  .then(@formatForAPI)
  .fail(@errorHandler)
  .done()

exports.validateRequest = (headers ,params) ->
  Q.Promise (resolve, reject, notify) ->
    console.log '1) valid Request'
    if headers['example'] == 'hello' && params["id"]
      resolve params["id"]
    else
      reject new Error('Invalid Request', 400)

exports.loadFromDynamo = (id) ->
  Q.Promise (resolve, reject, notify) ->
    console.log '2) load Request' + id
    resolve {key: 'value'}

exports.formatForAPI = (item) ->
  Q.Promise (resolve, reject, notify) ->
    console.log '3) formatforapi'
    resolve item

exports.errorHandler = (err) ->
  console.log('error ' + err)
  return err

此处还有生成的javascript:

(function() {
  'use strict';
  var Q;
  Q = require('q');

  exports.awesome = function() {
    var headers, params;
    headers = {
      "example": "hello"
    };
    params = {
      "id": "J123456789012345678"
    };
    console.log('response is' + JSON.stringify(this.handleAPIRequest(headers, params)));
    console.log('awesome');
    return 'awesome';
  };

  exports.handleAPIRequest = function(headers, params) {
    return this.validateRequest(headers, params).then(this.loadFromDynamo).then(this.formatForAPI).fail(this.errorHandler).done();
  };

  exports.validateRequest = function(headers, params) {
    return Q.Promise(function(resolve, reject, notify) {
      console.log('1) valid Request');
      if (headers['example'] === 'hello' && params["id"]) {
        return resolve(params["id"]);
      } else {
        return reject(new Error('Invalid Request', 400));
      }
    });
  };

  exports.loadFromDynamo = function(id) {
    return Q.Promise(function(resolve, reject, notify) {
      console.log('2) load Request' + id);
      return resolve({
        key: 'value'
      });
    });
  };

  exports.formatForAPI = function(item) {
    return Q.Promise(function(resolve, reject, notify) {
      console.log('3) formatforapi');
      return resolve(item);
    });
  };

  exports.errorHandler = function(err) {
    console.log('error ' + err);
    return err;
  };

}).call(this);

以下是控制台中打印的内容:

1) valid Request
response is undefined
awesome
2) load RequestJ123456789012345678
3) formatforapi

我期待结果读取类似

的内容
1) valid Request
2) load RequestJ123456789012345678
3) formatforapi
response is item
awesome

0 个答案:

没有答案