我应该在Promise中使用return吗? [英] should i use `return` in Promise?

查看:1312
本文介绍了我应该在Promise中使用return吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function saveToTheDb(value) {  
  return new Promise(function(resolve, reject) {
    db.values.insert(value, function(err, user) { // remember error first ;)
      if (err) {
        return reject(err); // don't forget to return here
      }
      resolve(user);
    })
  }
}

这是我从此处中看到的代码. 我对return关键字感到困惑.

Here is the code which i see from here. i am confused about return keyword.

对于resolve(user);,我需要return吗?

对于reject(user);,我需要return吗?

推荐答案

new Promise()回调中无需使用return语句. Promise构造函数不希望回调返回任何形式的值.

There is no need to use a return statement inside a new Promise() callback. The Promise constructor is not expecting any sort of return value from the callback.

因此,在该回调中使用return语句的原因仅是为了控制该函数中的执行流程.如果要在回调中完成执行而不再执行该回调中的代码,此时您可以发出return;.

So, the reason to use a return statement inside that callback is only to control the flow of execution in that function. If you want execution inside your callback to finish and not execute any more code within that callback, you can issue a return; at that point.

例如,您可能没有return语句就这样编写了代码:

For example, you could have written your code like this with no return statement:

function saveToTheDb(value) {  
  return new Promise(function(resolve, reject) {
    db.values.insert(value, function(err, user) { 
      if (err) {
        reject(err);
      } else {
        resolve(user);
      }
    });
  }
}

在这种情况下,您使用了if/else子句来确保函数中的控制流采用正确的路径,并且不需要或不使用return.

In this case, you used the if/else clause to make sure the flow of control in your function takes the correct path and no return was needed or used.

在散布这样的异步函数时,常见的快捷方式是:

A common shortcut when promisifying async functions like this is:

function saveToTheDb(value) {  
  return new Promise(function(resolve, reject) {
    db.values.insert(value, function(err, user) { 
      if (err) return reject(err);
      resolve(user);
    });
  }
}

这在功能上与先前的代码块没有什么不同,但是它的键入更少,结构更紧凑. reject(err);前面的return语句仅出于控制流程的原因,以防止在发生错误的情况下执行resolve(user);语句,因为所需的控制流程是调用reject(err),然后不执行其他任何操作.回调.

This is not functionally different than the previous code block, but it is less typing and more compact. The return statement in front of reject(err); is only for flow of control reasons to prevent from executing the resolve(user); statement in case of error since the desired flow of control is to call reject(err) and then not execute anything else in the callback.

实际上,在此特定情况下,实际上甚至不需要最后一个块中的return语句,因为在reject()之后执行resolve()不会执行任何操作,因为将promise锁定到首先解析或拒绝的那一个.但是,通常认为执行不必要的代码是较差的做法,因此许多人认为使用if/elsereturn之类的控制结构流仅执行所需的代码会更好.

In fact, the return statement in this last block is not actually even needed in this specific case because executing a resolve() after a reject() will not do anything since promises are latched to whichever happens first resolve or reject. But, it is generally considered poor practice to execute unnecessary code so many would argue that it is better to use flow of control structures such as if/else or return to only execute the code that is needed.

因此,从技术上讲,这也是可行的,但由于它执行了不必要的代码并且结构也不太清晰,因此不被视为最佳实践:

So, this would technically work too, but is not considered a best practice because it executes unnecessary code and isn't as clearly structured:

function saveToTheDb(value) {  
  return new Promise(function(resolve, reject) {
    db.values.insert(value, function(err, user) {
      if (err) reject(err);
      resolve(user);
    });
  }
}


仅供参考,您在这里所做的事情叫做承诺",它使一个常规的异步函数(该函数与回调一起使用)成为一个返回诺言的函数.有一些库和函数可以在一个函数调用中为您实现"函数或函数的整个对象(例如,整个API),因此您不必手动执行此操作.例如,我经常使用Bluebird来提供Promise.promisify()来实现单个功能,或者使用Promise.promisifyAll()来实现对象或原型上的所有方法.这是非常有用的.例如,您可以通过以下方式获得整个fs模块的承诺版本:


FYI, what you are doing here is called "promisifying" which makes a regular async function that works with a callback into a function that returns a promise. There are libraries and functions that will "promisify" a function or a whole object of functions (e.g. a whole API) for you in one function call so you don't have to do this manually. For example, I regularly use Bluebird which offers Promise.promisify() for promisifying a single function or Promise.promisifyAll() which will promisify all the methods on an object or prototype. This is very useful. For example, you could get promisified versions of the entire fs module with just this:

var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));

然后,您可以使用返回承诺的方法,例如:

Then, you can use methods that return a promise such as:

fs.readFileAsync("file.txt").then(function(data) {
    // do something with file.txt data here
});

这篇关于我应该在Promise中使用return吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆