should i use `return` in Promise?

前端 未结 3 766
忘了有多久
忘了有多久 2020-12-02 18:48
function saveToTheDb(value) {  
  return new Promise(function(resolve, reject) {
    db.values.insert(value, function(err, user) { // remember error first ;)
      i         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 19:37

    Generally, in NodeJS, you shouldn't use the promise constructor very much.

    The promise constructor is for converting APIs that don't return promises to promises. You should consider using a library that provides promisification (even if you use native promises all-around) since it provides a safe alternative that does not have subtle errors with error-handling logic.

    Automatic promisification is also considerably faster.

    That said, the answer to your question is "Yes".

    It is perfectly safe to do so, there is nothing special about promise constructors - they are just plain JavaScript. Domenic discusses the design of the promise constructor in his blog.

    It is perfectly safe (just like any other function) to return early - it is actually quite common in regular asynchronous functions.

    (Also, in your example code you should just use Promise.resolve, but I assume it was that simple only because it is an example).

    Copied this answer from duplicate

提交回复
热议问题