使用投入承诺

时间:2016-04-15 16:18:13

标签: javascript node.js error-handling promise throw

我想创建一个返回promise的函数,如果有什么内容抛出错误,它会返回promise reject。

function promiseFunc(options) {
  return new Promise(() => {
    return options;
  });
}

function myfunc(options) {
  return new Promise(() => {
    if (!options) throw new Error("missing options");

    return promiseFunc(options).then((result) => {
      if (result.throwerr) throw new Error("thrown on purpose");

      return result.value;
    });
  });
};

我的测试如下:

const myfunc = require("./myfunc");

describe('myfunc', () => {
  it('should fail without options', () => {
    return myfunc()
      .then((result) => { throw new Error(result) }, (err) => {
        console.log("test #1 result:", err.message === "missing options");
      });
  });

  it('should fail on options.throwerr', () => {
    return myfunc({throwerr: true})
      .then((result) => {}, (err) => {
        console.log("test #2 result:", err.message === "thrown on purpose");
      });
  });

  it('should return options.value', () => {
    return myfunc({value: "some result", throwerr: false})
      .then((result) => {
        console.log("test #3 result:", result === "some result");
      }, (err) => {});
  });
});

第一次测试通过,但第二次和第三次测试失败。

日志#2甚至没有运行,所以我认为“故意抛出”会弄乱某些东西,因此我创建了测试#3,我没有抛出任何东西,但它仍然失败。 我错过了什么?

解决方案:

function promiseFunc(options) {
  return new Promise(resolve => {
    return resolve(options);
  });
}

function myfunc(options) {
  return new Promise((resolve, reject) => {
    if (!options) throw new Error("missing options");

    return promiseFunc(options).then(result => {
      if (result.throwerr) throw new Error("thrown on purpose");

      return resolve(result.value);
    }).catch(err => {
      return reject(err);
    });
  });
};

3 个答案:

答案 0 :(得分:1)

您忘记通过具有解决方案和拒绝参数的功能,因此您的承诺无法正常工作。

function promiseFunc(options) {
  return new Promise(resolve => { // resolve function
    resolve(options)
  })
}

module.exports = function myfunc(options) {
  return new Promise((resolve, reject) => { // since you may either resolve your promise or reject it, you need two params
    if (!options) {
      return reject(new Error("missing options"))
    }

    return promiseFunc(options).then(result => {
      if (result.throwerr) {
        return reject(new Error("thrown on purpose"))
      }
      resolve(result.value)
    })
  })
}

...和测试(摩卡)

const assert = require('assert'),
      myfunc = require("./myfunc")

describe('myfunc', () => {
  it('should fail without options', done => { // mind the callback, promises are always async
    myfunc()
      .catch(err => {
        assert(err.message === "missing options")
        done() // <- called here
      })
  })

   it('should fail on options.throwerr', done => {
      myfunc({throwerr: true})
         .catch(err => {
            assert(err.message === "thrown on purpose")
            done()
      })
   })

  it('should return options.value', done => {
    return myfunc({value: "some result", throwerr: false})
      .then(result => {
          assert(result === "some result")
          done()
       })
    })
 })

答案 1 :(得分:0)

我想创建一个返回promise的函数,如果有什么内容抛出错误,它会返回promise reject。

这样做......

var q = require('q'); // In recent versions of node q is available by default and this line is not required

function iReturnAPromise(num) {

    var def = q.defer();

    if (typeof num=== 'number') {

        try {
            var value = 100 / num;
            def.resolve(value);
        } catch(e) {
            def.reject("oops a division error - maybe you divided by zero");
        }
    } else {
        def.reject("o no its not a number");
    }
    return def.promise;
}

PS这个函数是徒手编码的,尚未经过测试 - 但这样可行。显然应该谨慎使用捕获。

PS我更喜欢使用promise的q库实现而不是默认的节点promise库 - 它们采用了一种非常不同的方法。 q免除所有包装!

答案 2 :(得分:0)

使用你想要的诺言库......

function iReturnAPromise(num) {


return new Promise(function(resolve, reject) {


    if (typeof num === 'number') {

        try {
            var value = 100 / num;
            resolve(value);
        } catch (e) {
            reject("oops a division error - maybe you divided by zero");
        }
    } else {
        reject("o no its not a number");
    }

})

}

iReturnAPromise(7).then(
    function(response) {console.log("success", response)},
    function(response) {console.log("failure", response)}
);

// Unexpectedly this is not an error in node 5.6 because div by 0 is not an error operation anymore!
iReturnAPromise(0).then(
    function(response) {console.log("success", response)},
    function(response) {console.log("failure", response)}
);

iReturnAPromise("fred").then(
    function(response) {console.log("success", response)},
    function(response) {console.log("failure", response)}
);

你可以看到为什么我更喜欢q语法:)