- Why Promise
- 避免回调地狱
- 可链式调用
- 支持try catch语法
- 有catch链式方法
- ajax调用
function getData(url, success, fail) { var ajaxRequest = new XMLHttpReqeust(); ajaxRequest.open('GET', url); ajaxRequest.onreadystatechange = function() { if(this.readystate !== 4) { return; } if(this.status === 200) { success(this.response); } else { fail(new Error(this.statusText)); } } ajaxRequest.send(); }
-
实例化
var promsie = new Promise(function(resolve, reject){})
- 将回调函数转化成Promise
Callback:var callbackFun = function(cb) { setTimeout(function(){ cb(); }, 1000); }
Promise:
var promise = function() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve(); }, 1000) }); } promise().then(function(){ cb(); });
- 手写node.js的util.promisify()方法
- util.promisefy方法
// fs.readFile var fs = require('fs'); // Commonjs fs.readFile('./text.json', 'utf-8', function(err, res){ console.log(res); }); //util.promisify() var readFilePromise = require('util').promisify(fs.readFile); readFilePromise('./text.json', 'utf-8').then(function(res) { console.log(res); }, function(err) {console.error(err)});
- 手写promisify
var fs = require('fs'); var promisify = function(fun) { return function(...args) { return new Promise(function(resolve, reject) { args.push(function(err, res) { if(err) reject(err); resolve(res); }) fun.apply(fun, args); }); } } var readFilePro = promisify(fs.readFile); readFilePro('./promise-test.js', 'utf-8').then(function(res) { console.log("test"); console.log(res); })
- util.promisefy方法
- Promise规范摘要
- 三种状态:等待(pending), 已完成(fulfilled), 已拒绝(rejected)
- thenable: then方法return一个promise; then可被调用多次;
- Promise静态方法
- Promise.resolve()
- Promise.reject()
- Promise.all([promise1, promise2])
- Promise.race()
- 面试题测试
//Q: 给出以下代码的输出 var promise = new Promise(function(resolve, reject){reject();}) promise.then(null, function() { console.log('promise status is rejected'); return 123 }) .then(null, null) .then(null, null) .then(function(res) { console.log(res); console.log("promise status is completed"); }, function(e) { console.log(e); console.log("promise status is rejected finally"); }); //Output is: // promise status is rejected // 123 // promise status is completed
Promise摘要笔记
最新推荐文章于 2024-08-14 15:45:18 发布