简体   繁体   English

为什么需要使用 promise 作为异步回调的包装器

[英]Why need to use promise as a wrapper for asynchronous callbacks

I am new to JS and wanted to understand Promise is JS.我是 JS 新手,想了解 Promise 就是 JS。 So far, I got that Promises are not asynchronous, that is, as you can see in the code below new Promise( function ( ) { console.log( 'b' ); setTimeout( function ( ) { console.log( 'D' ); }, 0 ); } );到目前为止,我知道 Promises 不是异步的,也就是说,正如你在下面的代码中看到的new Promise( function ( ) { console.log( 'b' ); setTimeout( function ( ) { console.log( 'D' ); }, 0 ); } ); When promise object is returned only setTimeOut is executed asychronously and promise serves as a wrapper for that setTimeOut.当 promise 对象返回时,只有 setTimeOut 异步执行,promise 充当该 setTimeOut 的包装器。 The question is why need to wrap asynchronous code like setTimeOut inside promise or Ajax requests done with XHR object inside promise.问题是为什么需要在 promise 中封装异步代码,如 setTimeOut 或在 promise 中使用 XHR 对象完成的 Ajax 请求。

For sure you don't have to use Promises, you can do everything just with callbacks.当然,您不必使用 Promises,您只需使用回调即可完成所有操作。 But callbacks itself don't really scale well, in the sense that multiple of them don't work together that well.但是回调本身并不能很好地扩展,因为它们中的多个不能很好地协同工作。

For example, lets take an asynchronous function that creates a new user account:例如,让我们使用一个创建新用户帐户的异步函数:

  User.create("jonas", result => {
    alert("New account created");
  });

Now, lets create 10 accounts ... Oh right, how does that work?现在,让我们创建 10 个帐户......哦,对了,这是如何工作的? Try it, and you'll see that it is far more complicated.尝试一下,您会发现它要复杂得多。 And thats were Promises get relevant.这就是 Promise 的相关性。 If User.create() would create a promise, we can easily use Promise.all or Promise.race on them, chain them with .then(...) ...如果User.create()会创建一个 promise,我们可以很容易地对它们使用Promise.allPromise.race ,用Promise.all .then(...) ...

  Promise.all([
    User.create("jonas"),
    User.create("MM")
  ]).then(result => {
    alert("Two users were created");
  });

Sidenote: Promises only make sense if you resolve them somewhen, so a good example would be:旁注:承诺只有在你resolve它们时才有意义,所以一个很好的例子是:

  function timer(time) {
    return new Promise( function (resolve) { 
      console.log("promise created synchronously"); 
      setTimeout( function ( ) {
       console.log("callback called asynchronously and promise resolved");
       resolve();
     }, time); 
   });
 }

timer(100).then(/*...*/);

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

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