Promise、Async和Await
Promise
在javascript中promises被用来处理asynchronous操作。当有多任务要处理时,就需要异步,这里面主要问题就是需要知道任务处理的结果,callback回调的代码就需要多层的嵌套
,形成一个callback hell回调深渊。让代码难于管理。 Promise就提供了更好的处理错误,相对events and callbacks。
promise就像现实世界里面的承诺一样, 每个承诺都有两种结果:要么遵守要么没有。Javascript的promise也一样。我们定义一个promise,它要么是resolved,要么是rejected.
promise也是个object,他会产生一个值: 要么是处理成功的value,要么是没处理成功的原因。它有2个属性 properties(财产): state 和 result.
promise的state有: pending, fulfilled or resolved, rejected; 分别表示处理中、完成、没完成承诺。,请求没返回前就是pending,返回的是可能是完成or失败。
下面是关键了,a promise对象可以通过Promise constructor创建.
在javascript中promises被用来处理asynchronous操作。当有多任务要处理时,就需要异步,这里面主要问题就是需要知道任务处理的结果,callback回调的代码就需要多层的嵌套
,形成一个callback hell回调深渊。让代码难于管理。 Promise就提供了更好的处理错误,相对events and callbacks。
promise就像现实世界里面的承诺一样, 每个承诺都有两种结果:要么遵守要么没有。Javascript的promise也一样。我们定义一个promise,它要么是resolved,要么是rejected.
promise也是个object,他会产生一个值: 要么是处理成功的value,要么是没处理成功的原因。它有2个属性 properties(财产): state 和 result.
promise的state有: pending, fulfilled or resolved, rejected; 分别表示处理中、完成、没完成承诺。,请求没返回前就是pending,返回的是可能是完成or失败。
下面是关键了,a promise对象可以通过Promise constructor创建.
let promise = new Promise(function(resolve, reject){ //statements })
promise构造函数把callback function当作一个参数: function(resolve,reject){...} 这就是回调函数,也是参数。这个回调函数又有2个参数:resolve作为成功的参数,reject作为失败的参数。
这个包含在new Promise对象里面的回调函数 被称为执行人executor, 当声明一个新的promise,这个executor执行人会自动执行, 一个promise consists of 生产者代码和消费者代码。
生产者代码是一组状态,执行一些操作,得到的结果被用于 消费者。
消费者是一组状态,然后等生产者的结果,一个promise是一个javascript对象,连接生产和消费。
let promise = new Promise(function(resolve, reject) { // producing code const a = "hello"; const b = "Hello" if(a === b) { resolve(); // call on fulfilled promise. }else { reject(); // call on rejected promise. }}); // consuming code, waiting for a promise to be resolved or fulfilled. promise.then(function () { console.log('The promise is fulfilled.'); }).catch(function () { console.log('The promise is rejected.'); }); //Output//The promise is rejected.
then() 的2个参数依次是 回调函数executor的resolve和reject。
catch()处理reject或者异常
如果有多个promise转换成数组
Promise.all()静态方法 takes an iterable of promises as an input, returning a single promise to an array of input promises. This returned promise will resolve when all input promises have been resolved, or rejected if any of the input promises has been rejected.
catch()处理reject或者异常
如果有多个promise转换成数组
Promise.all()静态方法 takes an iterable of promises as an input, returning a single promise to an array of input promises. This returned promise will resolve when all input promises have been resolved, or rejected if any of the input promises has been rejected.
const p1 = Promise.resolve(10);
const p2 = 50;
const p3 = new Promise((resolve, reject) => {
setTimeout(resolve, 200, 'Hello');
});
Promise.all([p1, p2, p3]).then((value) => {
console.log(value);
});
//Output
//Array [10, 50, "Hello"]
一个现实生活中的例子:公司promise 承诺24小时客服电话,但是电话因为人员不够或者故障接不通。
let promise = new Promise(function(resolve, reject) { if (没有空闲){ reject("busy") }else { resolve("转接中") } }) promise.then(function(success){ console.log(success) },function(err){ console.log(err) })
async和await是promise的扩展
Async
"async" 常常被用在关键字“function”前面,当定义一个 function 并让这个function 在执行后返回 一个 promise。看例子
语法Syntax
async function function_name() { // body of function }
<!DOCTYPE html>
<html>
<body>
<h1> Async/Await in JavaScript </h1>
<script>
async function fun() { return "Async keyword"; } // OR async function fun() { return Promise.resolve("Async keyword");} console.log(fun()); </script> </body> </html>
We can capture the promise and extract value from it in the above code since the value returned is a promise. Using “then”, we may attach a callback function with the promise.
For example,
<!DOCTYPE html>
<html>
<body>
<h1> Async and Await in JavaScript </h1>
<script>
async function fun() { return "Async keyword"; }
fun().then((data) => { console.log(data)});
</script>
</body>
</html>
Async Function Expression
Syntax
let function_name = async function(){ // body of function }
<!DOCTYPE html>
<html>
<body>
<h2> Async and Await in JavaScript </h2>
<script>
let fun = async function(){ return "Async Function Expression";}
fun();
</script>
</body>
</html>
Async Arrow Function
Syntax
let function_name = async () => { // body of function }
<!DOCTYPE html>
<html>
<body>
<h1> Async and Await in JavaScript </h1>
<script>
let fun = async()=>{ return "Async Arrow Function";}
fun();
</script>
</body>
</html>
<html>
<body>
<h1> Async and Await in JavaScript </h1>
<script>
let fun = async()=>{ return "Async Arrow Function";}
fun();
</script>
</body>
</html>
Await keyword
我们只能在async函数里面使用await,await用在function前面去为了等待promise返回一个值。
Syntax
let value = await promise;
let value = await promise;
<!DOCTYPE html>
<html>
<body>
<h1> Async and Await in JavaScript </h1>
<h2 id='message'></h2>
<script>
async function fun() {
var promise1 = new Promise(function(Res, Rej){ Res("Hello, World!!");});
document.getElementById("message").innerHTM = await promise1; } fun(); </script> </body> </html>
There would be a syntax issue if we tried to use await keyword in a non-async function or regular function. For example,
<!DOCTYPE html><html><body> <h2> Async and Await in JavaScript </h2><script>
function fun() {
let promise = Promise.resolve('Hello, World!!!');
let result = await promise; // SyntaxError: await is only valid in async functions.
}
fun();
</script></body></html>
When the Await and Async keywords are used together, the main thread will not continue to execute further until the asynchronous portion of the application has been completed, giving the thread synchronous behavior. Thus, Await and Async in JavaScript have introduced synchronous behavior to the Execution.
I hope this module will be beneficial & now you have got some basic knowledge of Async and Await in JavaScript. In the beginning, it will take some time for you to understand it properly, but by practicing it, you will get to know about it. In the next module, I will be discussing Destructuring in JavaScript. You can refer to our website for other exciting & valuable modules like this.
https://usemynotes.com/async-and-await-in-javascript
阅读量: 663
发布于:
修改于:
发布于:
修改于: