简体   繁体   English

承诺中的退货声明

[英]Return statement in promises

I'm writing a simple controller for a GET request in node.js that uses promises. 我正在为使用promise的node.js中的GET请求编写一个简单的控制器。 The code works, but I'm not 100% sure why. 该代码有效,但我不确定100%为什么。 I have a getStoriesHelper function that returns a promise, and after I get the result, it does return res.json(listOfStories); 我有一个getStoriesHelper函数,它返回一个promise,得到结果后,它确实return res.json(listOfStories); . This works, but I was under the impression that returns only breaks out of a single function scope (so I assume it should only break out of the anonymous function scope), and just wondering why it would break out of the getStories function as well? 这行得通,但是我给人的印象是,返回仅超出单个函数范围(因此我认为应该只超出匿名函数范围),并且只是想知道为什么它也将超出getStories函数?

//for instance, the return statement only breaks out of the anonymous function and not from dummy()
function dummy() {
    _.map([1, 2, 3], function(element) {
        return element * 2;
    }
}

//node.js controller
exports.getStories = function(req, res) {
  var studentId = req.params.studentId;

  User.findOne({role: 'student', _id: studentId}).exec()
    .then(function(student) {
      var isNursery = student.status === 'attending class' && user.bookLevel === 'nursery';

      getStoriesHelper(student, isNursery).then(function(listOfStories) {
        //shouldn't return only break out of this inner function scope
        return res.json(listOfStories)
      });
    });
};

//dummy async code
function getStoriesHelper() {
  var deferred = Q.defer();
  setTimeout(function() {
    deferred.resolve(123)
  }, 3000);
  return deferred.promise;
}

Your code works because 您的代码有效,因为

  1. findOne and getStoriesHelper are asynchronous and res still is in scope within them. findOnegetStoriesHelper是异步的, res仍然在它们的范围内。

  2. The statement return res.json(listOfStories) does two things. 语句return res.json(listOfStories)做两件事。 it writes the response to the output stream as well as returns the value returned by res.json() which is never used, so in fact it won't harm if you do not return , the function is about to return already. 它将响应写入输出流,并返回从未使用过的res.json()返回的值,因此,如果您不return ,则该函数将已经return ,实际上不会造成损害。

  3. getStories function is already ended the moment you called an async function so don't think that inner return has any effect outside that anonymous function. 调用异步函数后, getStories函数已经结束,因此不要认为内部return对匿名函数没有任何影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM