使用承诺

Using throw in promises

我想创建一个 returns 承诺的函数,如果在其中抛出错误,它 returns 承诺拒绝。

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 甚至没有 运行,所以我假设 "throw on purpose" 搞砸了一些东西,因此我创建了测试 #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);
    });
  });
};

我想创建一个 returns 承诺的函数,如果其中有什么东西抛出错误,它 returns 承诺拒绝。

这样就可以了...

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 此函数是徒手编写的,尚未经过测试 - 但它会起作用。显然 try catch 应该谨慎使用。

PS 我更喜欢 promise 的 q 库实现,而不是默认的节点 promise 库——它们采用了非常不同的方法。 q 省去所有包装!

您忘记传递带有 resolve 和 reject 参数的函数,所以您的承诺不起作用。

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)
    })
  })
}

...和测试 (mocha)

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()
       })
    })
 })

使用你想要的 promise 库...

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 语法了:)