Home > Web Front-end > JS Tutorial > Detailed explanation of Promises asynchronous issues_javascript skills

Detailed explanation of Promises asynchronous issues_javascript skills

WBOY
Release: 2016-05-16 15:32:28
Original
1355 people have browsed it

By now, probably every JavaScript developer and their grandmother has heard of Promises. If you haven't, you're about to. The concept of promises was proposed by members of the CommonJS team in the Promises/A specification. Promises are increasingly used as a way to manage callbacks for asynchronous operations, but by their design they are far more useful than that. In fact, due to their multiple uses, countless people have told me - after I've written something about promises - that I'm "missing the point" of promises. So what is the point of promises?

Something about Promises

Before I get into the "nitty gritty" of promises, I thought I'd give you a little inside look at how they work. A promise is an object that—according to the Promise/A specification—requires only one method: then. The then method takes three parameters: a success callback, a failure callback, and a forward callback (the specification does not require the implementation of forward callbacks to be included, but many do). A new promise object is returned from each then call.
A promise can be in one of three states: unfulfilled, completed, or failed. A promise starts in an unfulfilled state. If it succeeds it will be completed, if it fails it will be failed. When a promise moves to the completion state, all success callbacks registered for it will be called and the success result value will be passed to it. In addition, any success callback registered to the promise will be called immediately after it has completed.

The same thing happens when the promise moves to the failed state, except it calls the failure callback instead of the success callback. For implementations that include progress features, a promise can update its progress at any time before it leaves the unfulfilled state. When progress is updated, all progress callbacks are passed the value of progress and are called immediately. Progress callbacks are handled differently than success and failure callbacks; if you register a progress callback after a progress update has occurred, the new progress callback will only be called for the updated progress after it has been registered.
We won't go further into how promise state is managed because that's outside the specification and each implementation differs. In later examples you'll see how it's done, but for now that's all you need to know.

Handling callbacks

Handling callbacks for asynchronous operations as mentioned earlier is the most basic and common use of promises. Let's compare a standard callback with a callback using promises.

// Normal callback usage
asyncOperation(function() {
  // Here's your callback
});
// Now `asyncOperation` returns a promise
asyncOperation().then(function(){
  // Here's your callback
});
Copy after login

I doubt anyone would actually care to use promises just by seeing this example. There seems to be no benefit, except that "then" makes it more obvious that the callback function is called after the asynchronous operation is completed. But even with this benefit, we now have more code (abstraction should make our code shorter, right?) and promises are slightly less performant than standard callbacks.

But don’t let this stop you. If this were the best that promises could do, this article wouldn't exist

Pyramid of Doom

// Normal callback usage => PYRAMID OF DOOOOOOOOM
asyncOperation(function(data){
  // Do some processing with `data`
  anotherAsync(function(data2){
    // Some more processing with `data2`
    yetAnotherAsync(function(){
      // Yay we're finished!
    });
  });
});
// Let's look at using promises
asyncOperation()
.then(function(data){
  // Do some processing with `data`
  return anotherAsync();
})
.then(function(data2){
  // Some more processing with `data2`
  return yetAnotherAsync();
})
.then(function(){
  // Yay we're finished!
});
Copy after login

正如你所见,promises的使用使得事情变扁平而且更可读了。这能起作用是因为——像早先提到的——then返回了一个promise,所以你可以将then的调用不停的串连起来。由then返回的promise装载了由调用返回的值。如果调用返回了一个promise(像这个例子中的情形一样),then返回的 promise装载了与你的回调返回的promise所装载的相同值。这内容很多,因此我将帮助你一步一步的理解它

异步操作返回一个promise对象。因此我们在那个promise对象中调用then,并且传给它一个回调函数;then也会返回一个promise。当异步操作结束,它将给promise装上数据。然后(第一次)回调被调用,数据被作为参数传递进去。如果回调不含有返回值,then返回的promise将会立即不带值组装。如果回调返回的不是一个promise,那么then返回的 promise将会立即装载那个数值。如果回调返回一个promise(像例子中的),那么then返回的 promise将等待直到我们回调返回的promise被完全装载。一旦我们回调的 promise被装载,它装载的值(本例中就是data2)将会被提交给then的promise。然后then中的promise装载了data2。等等。听起来有点复杂,但事实上很简单,如果我说的你不能理解,我非常抱歉。我猜我可能不是谈论它的最佳人选。

用命名的回调替代

但显然 promises 不是使这个结构扁平化的唯一方法。在写了一篇提到promises解决了厄运的金字塔问题的帖子之后,有个人对该帖评论说……

我想promises有时是有用的,但是“嵌套”的回调的问题(圣诞树综合症)可以仅用一个命名的函数作为一个参数替代匿名函数的方法平常的处理:

asyncCall( param1, param2, HandlerCallback );
function HandlerCallback(err, res){
// do stuff
}
Copy after login

它的例子只是给出了一层深的例子,但它仍是正确的。我们来扩展我前面的例子,使这个看起来容易些。

命名回调

// Normal callback usage => PYRAMID OF DOOOOOOOOM
asyncOperation(handler1);
function handler1(data) {
  // Do some processing with `data`
  anotherAsync(handler2);
}
function handler2(data2) {
  // Some more processing with `data2`
  yetAnotherAsync(handler3);
}
function handler3() {
  // Yay we're finished!
}
Copy after login

看看上面的代码!他们绝对是对的!它就是一个扁平的结构,但是这里有个问题同样也存在于 我以前从来没有注意过的老的回调例子中:依赖性和复用性。依赖性和复用性是相互关联的可逆类型。一样东西依赖的越少,那么它的复用性就越大。在以上的例子中,handler1依赖handler2,handler2依赖handler3.这就意味着handler1无论出于任何目的都不可在被用除非handler2也呈现出来。假如你不打算重用他们,那么给你的函数命名又有什么意义呢?

最糟糕的的是handler1都不关心在handler2里面发生了什么事情。它压根就不需要handler2除了和它异步工作。因此,让我们消除这些依赖性然后通过用promise使函数更具复用性。

链式回调

asyncOperation().then(handler1).then(handler2).then(handler3);
function handler1(data) {
  // Do some processing with `data`
  return anotherAsync();
}
function handler2(data2) {
  // Some more processing with `data2`
  return yetAnotherAsync();
}
function handler3() {
  // Yay we're finished!
}
Copy after login

这样看起来是不是好多了?假如另外的函数存在的话,现在handler1和handler2都互不相关了。想看看他们是否真的很棒呢?现在handler1可以被用在不需要handler2的情况下了。相反,handler1被操作以后,我们将可以用另一个handler。

复用函数

asyncOperation().then(handler1).then(anotherHandler);
function handler1(data) {
  // Do some processing with `data`
  return anotherAsync();
}
function anotherHandler(data2) {
  // Do some really awesome stuff that you've never seen before. It'll impress you
}
Copy after login

现在handler1已经从handler2脱离而且可以被用在了更多的情形中,特别是那些由handler2提供的功能而我们又不想用的。这就是复用性!评论家解决代码易读性的唯一方法就是通过消除缩进。我们不想消除缩进仅仅是为了缩进。多层次的缩进仅仅是某些事情错误的标志,问题不一定在它本身。他就像是由脱水引起的头痛。真正的问题是脱水,不是头痛。解决的方法是获得水合物,而不是用一些止痛药。

并行异步操作

在前面我提到的文章里,我将promises与events在处理异步操作方面做了比较。遗憾的是,按照那些曾提到过的人在评论里给的说法,我比较的不是很成功。我描述出了promises的力量,接着转到events来描述它们的力量,就像在我的特别项目里用到的那样。没有比较和对比。一位评论者写道(修改了一点语法错误):

我想用帖子中的例子是一个坏的对照。有篇论文证明了promises的值将会怎样,如果按下虚构的“启动服务器按钮”,将不仅仅是启动一个web服务器,还有一个数据库服务器,当它们都在运行的时候只是更新了UI。

使用promise的.when方法将会使这种“多个异步操作”例子变得普通,然而响应多个异步事件需要一个并不普通的代码量。
他完全正确。事实上我没有比较那两种情况。那篇文章的要点实际在于说明promises不是异步操作的唯一机制,而且在一些情况下,它们也不一定是最好的。在这个评论者指出的情况下,promises当然是最佳的解决办法。我们来看看他说的是什么

jQuery 具有 一个名为when的方法 ,可以带上任意数量的promise参数,并返回一个单一的promise。如果任何一个promise传入失败,when返回的promise也会失败。如果所有的promises被装载,那么每个值都将会按照promises被定义的顺序传递给附加的回调。

以并行的方式执行无数的异步操作非常有用,然后只要在它们之中的每一个结束之后继续执行回调。我们看一个简单的例子。

jQuery.when

// Each of these async functions return a promise
var promise1 = asyncOperation1();
var promise2 = asyncOperation2();
var promise3 = asyncOperation3();
// The $ refers to jQuery
$.when(promise1, promise2, promise3).then(
  function(value1, value2, value3){
    // Do something with each of the returned values
  }
);
Copy after login

People often say this is one of the best things about promises, and it’s part of what makes promises important. I also think this is a good feature that simplifies a lot of operations, but the mechanism of this when method is not mentioned in any Promises specification at all, so I don't think it is the point of Promises. There is a specification that mentions the when method, but it is completely different from the above. As far as I know, jQuery is the only library that implements this when method. Other promises libraries, such as Q, Dojo, and when implement the when method according to the Promises/B spec, but do not implement the when method mentioned by the commentator. However, the Q library has an all method, and when.js also has a parallel method, which works the same as the jQuery.when method above, except that they accept an array type parameter instead of an arbitrary number of parameters.

Representation of value

Promise is a better way to handle the following scenarios:

"I want to find a user in this database, but the find method is asynchronous."

So, here we have a find method that cannot return a value immediately. But ultimately it does "return" a value (via a callback), and you want to handle that value in some way. Now, by using a callback, you can define a continuation, or "some code that will handle that value at a later time"

Promise changes the "hey, here's some code you'll find yourself using to handle return values". They are methods that allow the "find" method to say "Hey, I'm going to be busy looking for the information you're looking for, but in the meantime you can continue to wait for the result to be returned, and you can process it in any way you want at the same time, like Real stuff! ”

Promise represents a real value. That's the trap. They work when you handle Promises like real things. The JavaScript implementation of Promise expects you to pass it a callback function. This is just a "coincidence", it is not an important thing.

I believe this is really the point of promises. Why? Read the first sentence of the Promise/A specification, "A promise represents the value returned by a completion of an operation." Makes it a bit obvious, doesn't it? Well, even if that's the point, that doesn't stop me from presenting other people's insights later in this article. Anyway, let’s talk a little more about this idea.

Conclusion

The point of a promise is that it represents the final result value returned by an operation, but the reason for using them is to make synchronous operations better parallel. Ever since asynchronous programming entered the scene, callbacks have popped up everywhere, obscuring our code in strange ways. Promise is a way to change it. Promises allow us to write code in a synchronous manner while giving us asynchronous execution of the code.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template