美文网首页
ES6-Promise

ES6-Promise

作者: 若沫成海 | 来源:发表于2019-06-26 16:32 被阅读0次

promise 是异步编程的一种解决方案。
三种状态:pending(进行中)、fulfilled(已成功)和rejected(已失败)
Resolved()表示成功,Reject()表示失败

new Promise(function(Resolved,Reject){ Resolved() })
.then(
function(){ //成功 },
function(){ //失败 })  //成功
new Promise(function(Resolved,Reject){ Reject() })
.then(function(){ //成功 })
.cath(function(){ //失败 })//失败

Promise 用new创建实例,新建后立即执行。
调用resolve函数和reject函数时带有参数,那么它们的参数会被传递给回调函数.

new Promise(function(Resolved,Reject){ Resolved('成功') })
.then(function(succ){ console.log(succ)//成功
},
function(){ 
//失败
})  

能无限回调
.then().then() ...
.catch().catch()...
上一个函数的返回值是下一个函数的传参

Promise 内部的错误不会影响到 Promise 外部的代码

const someAsyncThing = function() {
  return new Promise(function(resolve, reject) {
    // 下面一行会报错,因为x没有声明
    resolve(x + 2);
  });
};

someAsyncThing().then(function() {
  console.log('everything is great');
});

setTimeout(() => { console.log(123) }, 2000);
// Uncaught (in promise) ReferenceError: x is not defined
// 123

throw 抛出异常 后面的代码不能执行
console.warn() 警告
new Error()报错
finally方法用于指定不管 Promise 对象最后状态如何,都会执行的操作。
Promise.race竞速方法 速度最快执行完成功就成功失败就失败,其他的不在执行

// 生成一个Promise对象的数组
const promises = [2, 3, 5, 7, 11, 13].map(function (id) {
  return getJSON('/post/' + id + ".json");
});

Promise.all(promises).then(function (posts) {
  // ...
}).catch(function(reason){
  // ...
});

Promise.all规整方法 会同时开始执行 都是成功就都会成功,只要有一个失败就失败,不继续.
注意,如果作为参数的 Promise 实例,自己定义了catch方法,那么它一旦被rejected,并不会触发Promise.all()的catch方法

Promise.resolve方法,将现有对象转为 Promise 对象.
Promise.reject(reason)方法也会返回一个新的 Promise 实例,该实例的状态为rejected。

Promise应用
1.加载图片,异步加载图片

const preloadImage = function (path) {
  return new Promise(function (resolve, reject) {
    const image = new Image();
    image.onload  = resolve;
    image.onerror = reject;
    image.src = path;
  });
};

2.promise.try
不管是异步还是同步的函数,只是想用 Promise 来处理它,用then方法指定下一步流程,用catch方法处理f抛出的错误。
同步的函数直接用Promise就会变成异步的了

const f = () => console.log('now');
Promise.resolve().then(f);
console.log('next');
// next
// now

实现同步的方法
(1)用async函数

const f = () => console.log('now');
(async () => f())();
console.log('next');
// now
// next

(2)new Promise

const f = () => console.log('now');
(
  () => new Promise(
    resolve => resolve(f())
  )
)();
console.log('next');
// now
// next

(3)try

const f = () => console.log('now');
Promise.try(f);
console.log('next');
// now
// next

相关文章

网友评论

      本文标题:ES6-Promise

      本文链接:https://www.haomeiwen.com/subject/zmoccctx.html