Explanation of Promise in asynchronous programming in es6

一个新手
Release: 2017-09-30 09:25:58
Original
1200 people have browsed it

//引入模块let fs=require('fs'); //异步读文件方法,但是同步执行function read(url) { //new Promise 需要传入一个executor 执行器 //executor需要传入两个函数 resolve reject return new Promise((resolve,reject)=> { fs.readFile(url,'utf8',function (err,data) { if(err) { reject(err) } else { resolve(data); } }) } ) } ; //缺点 套了一个promise,而且捕获了2次,这两个请求没有依赖关系,时间叠加了// read('./name.txt').then((data)=> { // let obj= { } ; // obj.name=data; // read('./age.txt').then((data)=> { // obj.age=data; // console.log(obj); // } ,(err)=> { // console.log(err); // } )// // } , (err)=> { // console.log(err); // } ); //回调地狱 链式调用//相对好点的方法,同步两个异步依次执行 异常用catch捕获// let obj= { } ; // read('./name.txt').then((data)=> { // obj.name=data; // return read('./age.txt')// } ).then((data)=> { //如果promise返回promise可以继续then// obj.age=data; // return obj //将结果向下继续传递// } ).then((data)=> { // console.log(data) //单独处理结果// } ).catch((err)=> { // console.log(err)// } ); //all方法是promise是类上自带的方法,并发读取,失败一个都失败了,时间只是一个读取的时间//第一个参数 传递的是数组,数组装的是一个个promise对象//调用后会再次返回一个promise实例//最好的写法Promise.all([read('./name.txt'),read('./age.txt')]).then(([name,age])=> { //data就是promise执行成功的结果类型是数组 console.log( { name,age } ); } ).catch((err)=> { console.log(err) } )//race如果一个失败了,都失败,如果一个成功了都成功,很少用// Promise.race([read('./name.txt'),read('./age1.txt')]).then((data)=> { // //data就是promise执行成功的结果类型是数组// console.log(data); // } ).catch((err)=> { // console.log(err)// } )
Copy after login

The above is the detailed content of Explanation of Promise in asynchronous programming in es6. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!