简体   繁体   English

承诺中的决心究竟做了什么?

[英]What does a resolve in a promise do exactly?

I am starting to learn about promises in Javascript and I am still not getting my head around it. 我开始学习Javascript中的承诺,我仍然没有理解它。 The code below is mostly real code. 下面的代码主要是真实的代码。 I have placed several debugger statements so the program stops and I can understand how the flow works and inspect some variables. 我已经放置了几个调试器语句,所以程序停止了,我可以理解流程如何工作并检查一些变量。 I have read some blog posts about promises and I still can't understand everything. 我已经阅读了一些关于承诺的博客文章,我仍然无法理解一切。 This is from an app which uses AngularJS and q library. 这是来自使用AngularJS和q库的应用程序。

Few questions: 几个问题:
1- What does deferred.Resolve() do exactly? 1- deferred.Resolve()究竟做了什么? What is it doing with response.data? 它对response.data做了什么? When I inspected the 'deferred' object and its 'promise' object, I couldn't see any trace for response.data. 当我检查'deferred'对象及其'promise'对象时,我看不到response.data的任何痕迹。

2- When I resumed execution after debugger #1, I thought the http post statement would run but execution jumped to the return statement. 2-当我在调试器#1之后恢复执行时,我认为http post语句会运行但是执行跳转到return语句。 I guess that's where the promise jumped in and the post will happen in the future? 我猜这是承诺的里程,而这个帖子将来会发生吗?

3- How do I know when the post will happen when the function returns? 3-如何在函数返回时知道帖子何时发生? The caller will get the return promise, what is the caller expected to do with it? 调用者将得到返回承诺,调用者期望用它做什么?

this.GetData = function() 
  {
    var data = blahblah;
    var deferred = this.$q.defer();
    debugger;  //1
    this.$http.post(someurl, data,
               {
                  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                              handleErrors: false
                           })
                            .then(function(response) {
                                debugger; //2
                               (domesomething...)
                               deferred.resolve(response.data);
                            },
                             function(error) {
                              (logerror...)
                              deferred.reject(error);

                });
                debugger; //3
                return deferred.promise;
    };

It's appropriate to use q.defer() (an explicit creation of a promise) when wrapping callback style code, "promisifying"... 在包装回调样式代码时,使用q.defer() (显式创建一个promise)是合适的,“promisifying”...

this.timeoutWithAPromise = function(msec) {
  let defer = q.defer();
  setTimeout(() => defer.resolve(), msec);
  return defer.promise;
};

The foregoing says: "Create a promise and return it right away. That promise will be fulfilled when msec has passed. 上述说法:“创造一个承诺并立即归还。当msec过去时,这个承诺将会实现。

Question 1: resolve() fulfills the promise, calling whatever function that's been set with then() , passing it whatever parameter was passed to resolve. 问题1: resolve()履行promise,调用then()设置的任何函数,传递任何参数传递给resolve。

Question 2: You're right, the async operation is begun and a promise for it's completion is returned right away. 问题2:您说得对,异步操作已经开始,并且会立即返回对其完成的承诺。

Question 3a: The post will begin (or the timeout will commence in my eg) on another thread as soon as that invocation is made. 问题3a:一旦调用完成,帖子将在另一个线程上开始(或者我的例如,超时将开始)。 It will continue concurrently with execution on this calling thread, until it completes, which you understand from Question 1, is done by resolving the promise, invoking it's then() . 它将继续与此调用线程上的执行同时进行,直到它完成,您从问题1中理解,通过解析promise, then()调用它then()

Question 3b: What is the caller to do with a returned promise? 问题3b:回复承诺的来电者是什么? Attach a block to it that you wish to run upon completion, possibly additional async actions. 在完成时附加一个您希望运行的块,可能还有其他异步操作。 Taking my example... 以我为榜样......

let self = this;
self.timeoutWithAPromise(1000).then(()=> {
    console.log('1000msec have passed');
    return self.timeoutWithAPromise(1000);
}).then(()=> {
    console.log('now, another 1000msec have passed');
    // ...

Rewriting your example, realizing that $http already conforms to promises... 重写你的例子,意识到$ http已经符合承诺......

var data = blahblah;
let headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
let config = { headers: headers, handleErrors: false };
let httpPromise = this.$http.post(someurl, data, config).then((response)=> {
    console.log('got a response. tell our caller about it');
    return response.data;
}).catch((error)=>
    console.log('got an error.  either handle it here or throw it');
    throw error;
});
// this is important:  return the httpPromise so callers can chain off of it
return httpPromise;

Now a caller can say: 现在来电者可以说:

let promiseToDoEvenMore = this.GetData().then((data)=> {
    console.log(data);
    return this.GetMoreData();  // etc.
});
return promiseToDoEvenMore;   // and so on

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

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