为什么Promise构造函数需要一个在完成时调用“resolve”的函数,但是“then”不会返回一个值呢? [英] Why does the Promise constructor require a function that calls 'resolve' when complete, but 'then' does not - it returns a value instead?

查看:453
本文介绍了为什么Promise构造函数需要一个在完成时调用“resolve”的函数,但是“then”不会返回一个值呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我深入研究承诺时,我的理解已经停止了以下问题,我没有找到讨论(我发现是<$ c的具体讨论$ c>承诺构造函数和 Promise '然后'函数 - 但不是讨论比较他们的设计模式)。






1。 承诺构造函数



从MDN文档我们使用了Promise构造函数(与我的添加评论):

  new Promise(function(resolve,reject){...}); //<  - 调用此阶段1 




解析拒绝。第一个
参数履行承诺,第二个参数拒绝。一旦我们的操作完成,我们可以
调用这些函数。







2。 然后功能



转到然后函数,可以在 Promise 对象(返回一个新的 Promise object),我们有以下功能签名如文档所述(加上我的评论):

  p.then(onFulfilled ,onRejected); 




链接



因为然后方法返回一个Promise,你可以很容易链接
调用。




  var p2 = new Promise(function(resolve,reject){
resolve(1); // < - 第一阶段再次
});

p2.then(function(value){
console.log(value); // 1
返回值+ 1; //< - 调用此阶段2
})然后(function(value){
console.log(value); // 2
});






我的问题 / p>

从上面的代码片段,对我来说,传递给 函数的值似乎很清楚阶段1 传递到下一个阶段(第一个然后函数)。 在阶段1中没有返回值。但是,在第2阶段,它是返回值,然后传递到下一个阶段(第二个然后函数)。



创建 Promise ,并使用然后函数对现有承诺(也返回一个 Promise ),只是一个历史的侥幸(一个需要调用回调但不返回任何东西,另一个返回一个值,但不调用回调)?



或者我错过了 Promise 构造函数使用与然后函数不同的设计模式的根本原因

解决方案

Promise 构造函数与然后方法,因为它们是为了不同的目的而设计的两个独立的东西。



Prom ise 构造函数仅用于 promisify 1 异步函数。实际上,正如你所说,它是建立在调用 解决方案 / 拒绝回调到异步地发送值,在这种情况下没有返回值。



Promise 构造函数本身确实采取这个解析器回调(它同步地通过 resolve reject )实际上是增强旧版延迟模式,并且< c c然后回调。

  var p = new Promise(function(res,rej){| var def = Promise.Deferred(); 
setTimeout(res,100 ); | setTimeout(def.resolve,100);
}); | var p = def.promise;

相反,然后回调是古典异步回调,附加功能,您可以从中返回。他们被异步调用以接收值。

  p.then (function(val){...}); 

总结差异:




  • 承诺是一个构造函数,而然后是一种方法

  • 承诺需要一个回调,而然后最多需要两个

  • Promise 同步调用其回调,而然后异步调用其回调

  • Promise 总是调用其回调,

    然后可能不会调用其回调(如果承诺不履行/拒绝)

  • 承诺传递解决/拒绝对回调承诺的功能,

    然后传递所调用的承诺的结果值/拒绝原因

  • Promise 调用其回调以执行副作用(调用拒绝 / 解决),

    然后调用其回调结果值(用于链接) Promise.resolve Promise.reject fetch ,...)。实际上,这些都是基于 Promise 构造函数提供的同样的承诺构造和解决/拒绝功能,尽管这不是它们的主要目的。 然后基本上提供了附加 onFulfilled / onRejected 回调的功能一个现有的承诺,这是相当直接的 Promise 构造函数。



    所有这些都使用回调只是巧合 - 不是一个历史的侥幸,而是一个语言功能的一部分。



    1:理想情况下,你永远不会需要这个,因为所有本机异步的API都返回承诺


    As I plunge into studying Promises, my understanding has halted on the following question that I do not find discussed (all I find are specific discussions of the Promise constructor, and the Promise 'then' function - but not a discussion that compares their design patterns).


    1. The Promise constructor

    From the MDN documentation, we have this use of the Promise constructor (with my comment added):

    new Promise(function(resolve, reject) { ... }); // <-- Call this Stage 1
    

    Function object with two arguments resolve and reject. The first argument fulfills the promise, the second argument rejects it. We can call these functions, once our operation is completed.


    2. The then function

    Moving on to the then function that can be called on a Promise object (which returns a new Promise object), we have the following function signature as described by the documentation (with my comments added): :

    p.then(onFulfilled, onRejected);
    

    Chaining

    Because the then method returns a Promise, you can easily chain then calls.

    var p2 = new Promise(function(resolve, reject) {
      resolve(1); // <-- Stage 1 again
    });
    
    p2.then(function(value) {
      console.log(value); // 1
      return value + 1; // <-- Call this Stage 2
    }).then(function(value) {
      console.log(value); // 2
    });
    


    My question

    From the above code snippet, it seems clear to me that the value passed to the resolve function in Stage 1 is passed on to the next stage (the first then function). There is no return value at Stage 1. However, it is the return value at Stage 2 that is passed on to the next stage after that (the second then function).

    Is this lack of correspondence between the design pattern for the creation of a Promise, and the use of the then function on an existing promise (which also returns a Promise), just a historical fluke (one requires calling a callback but returns nothing, and the other returns a value but does not call a callback)?

    Or am I missing an underlying reason why the Promise constructor utilizes a different design pattern than the then function?

    解决方案

    There is no correspondence between the Promise constructor and the then method because they are two independent things, designed for different purposes.

    The Promise constructor is only used for promisifying1 asynchronous functions. Indeed, as you say, it is built on invoking resolve/reject callbacks to asynchronously send values, and there are no return values in that case.

    That the Promise constructor itself does take this "resolver" callback (to which it synchronously passes resolve and reject) is in fact an enhancement of the older deferred pattern, and bears no intended similarity to the then callbacks.

    var p = new Promise(function(res, rej) {    |    var def = Promise.Deferred();
        setTimeout(res, 100);                   |    setTimeout(def.resolve, 100);
    });                                         |    var p = def.promise;
    

    The then callbacks in contrast are classical asynchronous callbacks, with the additional feature that you can return from them. They are being invoked asynchronously to receive values.

    p.then(function(val) { … });
    

    To sum up the differences:

    • Promise is a constructor, while then is a method
    • Promise takes one callback, while then takes up to two
    • Promise invokes its callback synchronously, while then invokes its callbacks asynchronously
    • Promise always invokes its callback,
      then might not invoke its callbacks (if the promise is not fulfilled/rejected)
    • Promise passes the capabilities to resolve/reject a promise to the callback,
      then passes the result value / rejection reason of the promise it was called on
    • Promise invokes its callback for the purpose of executing side effects (call reject/resolve),
      then invokes its callbacks for their result values (for chaining)

    Yes, both do return promises, though they share that trait with many other functions (Promise.resolve, Promise.reject, fetch, …). In fact all of these are based on the same promise construction and resolve/reject capabilities that also the Promise constructor provides, though that's not their primary purpose. then basically offers the ability to attach onFulfilled/onRejected callbacks to an existing promise, which is rather diametral to the Promise constructor.

    That both utilise callbacks is just coincidential - not a historical fluke, but rather coadaption of a language feature.

    1: Ideally, you would never need this because all natively asynchronous APIs return promises

    这篇关于为什么Promise构造函数需要一个在完成时调用“resolve”的函数,但是“then”不会返回一个值呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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