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

查看:34
本文介绍了我应该在 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);
    });
  }
}

<小时>

仅供参考,您在这里所做的称为promisifying",它将与回调一起使用的常规异步函数转换为返回承诺的函数.有些库和函数可以在一个函数调用中为您承诺"一个函数或整个函数对象(例如整个 API),因此您不必手动执行此操作.例如,我经常使用 Bluebird,它提供 Promise.promisify() 来承诺单个函数或 Promise.promisifyAll() 它将承诺一个对象或原型上的所有方法.这是非常有用的.例如,您可以获得整个 fs 模块的promisified 版本:


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天全站免登陆