简体   繁体   English

返回值和从函数返回 Promise.resolve() 的区别

[英]Difference between returning a value and returning Promise.resolve() from a function

I have problem in understanding that what happens when we simply return a value or when we return Promise.resolve() from a function.我无法理解当我们简单地返回一个值或从函数返回Promise.resolve()时会发生什么。 Specifically: I am trying to understand how promises chaining works.具体来说:我试图了解承诺链是如何工作的。 I am chaining methods and verifying whether the value reaches in the method which is last call to then .我正在链接方法并验证值是否到达最后调用then的方法中。 I just want to understand the difference between returning promises to then , returning Promise.resolve() to then , and returning just a value to then .我只是想了解将 promise 返回到then 、将Promise.resolve()返回到then以及只返回一个值到then之间的区别。

I have problem in understanding that what happens when we simply return a value or when we return Promise.resolve() from a function.我无法理解当我们简单地返回一个值或从函数返回Promise.resolve()时会发生什么。

So there are (at least) two different scenarios:所以有(至少)两种不同的场景:

In just any old function在任何旧函数中

If it's just any old function (not a then or catch callback), then the difference is that return value;如果它只是任何旧函数(不是thencatch回调),那么区别在于return value; directly returns the value, whereas return Promise.resolve(value);直接返回值,而return Promise.resolve(value); returns a promise fulfilled with that value.返回用该值实现的承诺 It changes how the calling code uses the result.它改变了调用代码使用结果的方式。 In the return value;return value; case, the calling code just directly uses it.情况下,调用代码只是直接使用它。 In the return Promise.resolve(value);return Promise.resolve(value); case, the calling code needs to consume the promise, just like any other promise (and can't assume that the promise is already settled, even though it is).在这种情况下,调用代码需要使用承诺,就像任何其他承诺一样(并且不能假设承诺已经解决,即使它已经解决)。

If the function is meant to be the start of a promise chain, you'd use return Promise.resolve(value);如果该函数旨在成为承诺链的开始,则可以使用return Promise.resolve(value); . . (There are use cases for this; for instance, if the function may or may not need to start an asynchronous process: In the branch that doesn't have to, you'd still return a promise because the branch that has to do something asynchronous has to return a promise.) If it isn't, you'd just use return value; (有一些用例;例如,如果函数可能需要或可能不需要启动异步进程:在不必启动的分支中,您仍然会返回一个承诺,因为必须执行某些操作的分支异步必须返回一个承诺。)如果不是,你只需使用return value; . .

In then or catch callbackthencatch回调中

I am trying to understand how promises chaining works.我试图了解承诺链是如何工作的。

In that case, you're talking about return value;在这种情况下,您正在谈论return value; vs. return Promise.resolve(value);return Promise.resolve(value); in a then or catch callback.thencatch回调中。 That's easy: There's no point at all to return Promise.resolve(value);这很简单:根本没有必要return Promise.resolve(value); in a then or catch callback, it's redundant and unnecessary overhead;thencatch回调中,这是多余且不必要的开销; just use return value;只使用return value; . .

then and catch always return promises. thencatch总是返回承诺。 If your callback returns a simple value ( return value; ), the promise is fulfilled with that value.如果您的回调返回一个简单的值( return value; ),则承诺将使用该值实现。 If your callback returns a thenable (loosely, a promise; eg, return Promise.resolve(value); ), then the promise returned by then / catch is resolved to that thenable: When the thenable is settled, the promise is settled the same way.如果你的回调返回一个thenable (松散地,一个承诺;例如, return Promise.resolve(value); ),那么then / catch返回的承诺被解析为那个 thenable:当 thenable 被解决时,承诺被解决相同方式。 (And if your then or catch callback throws an error, the promise is rejected with that error.) (如果您的thencatch回调引发错误,则承诺会因该错误而被拒绝。)

There are valid reasons to return a promise from a then or catch callback, if you're starting a new asynchronous process in that callback;如果您在该回调中启动新的异步进程,则有正当理由从thencatch回调中返回承诺; but if you have an immediate value ready, there's no point in wrapping it in a promise — then and catch already do that.但是如果你已经准备好了一个直接值,那么将它包装在一个 Promise 中是没有意义的—— then catch已经这样做了。

When you return Promise.resolve() , you wrap your result into a Promise, on which you can call then and make chain of then .当您返回Promise.resolve() ,您将结果包装到一个 Promise 中,您可以在其上调用then并创建then链。 This is preferable for a single type returns.这对于单一类型的返回是可取的。

 function resolve() { return Promise.resolve(15); } resolve().then(value => console.log(value));

If you have a logic which depends on a call to the server and also you can have that result in the cache , you can have a function which in all cases returns you a Promise, so you can add then for the result of the Promise.如果您的逻辑依赖于对服务器的调用,并且您可以在cache获得该结果,那么您可以拥有一个在所有情况下都返回一个 Promise 的函数,因此您可以为 Promise 的结果添加then Look at this pseudo-code.看看这个伪代码。

I want my function in all cases return a Promise.我希望我的函数在所有情况下都返回一个 Promise。 So here if I have cached the userId I can just wrap the result into the Promise with Promise.resolve所以在这里,如果我已经缓存了userId我可以使用Promise.resolve将结果包装到 Promise 中

function getUserData() {
   if(cache.hasUserId) {
      return Promise.resolve(cache.hasUserId); // Is used to let the `then` functions to be called
   } else {
      return myAjaxCall();
   }
}

getUserData().then(userId => /* */);

Base on comment.基于评论。 Wrap into the Promise.resolve()包装到Promise.resolve()

 function add1(data) { return new Promise(function (resolve, reject) { resolve(data + 1); }); } function add2(data) { return Promise.resolve(data + 2); } function printdata(data) { console.log(data); }

A Promise is a proxy for a value not necessarily known when the promise is created. Promise是在创建Promise时不一定知道的值的代理。 It allows you to associate handlers with an asynchronous action's eventual success value or failure reason.它允许您将处理程序与异步操作的最终成功值或失败原因相关联。 This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.这让异步方法可以像同步方法一样返回值:异步方法不是立即返回最终值,而是返回在未来某个时间点提供值的承诺。 MDN MDN

The Promise.resolve(value) method returns a Promise object that is resolved with the given value. Promise.resolve(value)方法返回一个使用给定值解析的 Promise 对象。 If the value is a thenable (ie has a "then" method), the returned promise will "follow" that thenable, adopting its eventual state;如果值是一个 thenable(即有一个“then”方法),返回的 promise 将“跟随”那个 thenable,采用它的最终状态; if the value was a promise, that object becomes the result of the call to Promise.resolve;如果该值是一个承诺,则该对象成为对 Promise.resolve 调用的结果; otherwise the returned promise will be fulfilled with the value.否则返回的承诺将用该值实现。 MDN Promise.reslove MDN Promise.reslove

Returning a value from a function is synchronous unlike Promise.resolve()Promise.resolve()不同,从函数返回值是同步的

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

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