markdown JS承诺

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown JS承诺相关的知识,希望对你有一定的参考价值。

Promises are very similar to a promise in real life, they can be kept or broken. Promise object is data returned by asynchronous function. It can be a **resolve** if the function returned successfully or a **reject** if function returned an error.

A Promise is in one of these states:

- Initial state, neither fulfilled or rejected - _pending_
- The operation completed successfully - _fulfilled_
- The operation failed - _rejected_

This is how a promise is created:

```
var promise = new Promise(function(resolve, reject){
  /* executor */
});
```

The function that is passed to new Promise is called executor and takes two parameters, 
resolve and reject (also functions). The resolve and reject functions, when called, 
resolve or reject the promise, respectively. When the promise is created, this executor 
function runs automatically. 
Here is an example with a simple _setTimeout_ function:

```
var promise = new Promise(function (resolve, reject) { 
  setTimeout(() => resolve("done!"), 2000);
});
```

After two seconds of processing the executor calls resolve(“done!”), to produce the 
results from “pending” (results = undefined) to resolved(result=“done”) and since 
it’s resolved it has “fulfilled” the promise. Here is an example of the executor 
rejecting the promise with an error:

```
var promise = new Promise(function (resolve, reject) { 
  setTimeout(() => reject(new Error("fail!"), 2000);
});
```

The executor does a job, usually something that takes time, and than calls reject or 
resolve to change the state of the promise object. The executor should only call 
resolve or reject once, the promise’s state is final and further calls will be 
ignored. Promises can give us flexibility and better code flow. To summarize, 
the promise object represents the completion or failure of an asynchronous 
operation and its resulting value.

以上是关于markdown JS承诺的主要内容,如果未能解决你的问题,请参考以下文章

markdown JS承诺

markdown JS承诺

markdown 回调,承诺,异步等待

markdown 承诺

markdown 承诺和交付(也是未来)

markdown 挑战04:承诺