第30章 Promise 对象

1 Promise 的含义

1.1 概念

        Promise 是异步编程的一种解决方案。所谓Promise,简单说就是一个容器,里面保存着某个未来才会结束的事件(通常是一个异步操作)的结果。有了Promise对象,就可以将异步操作以同步操作的流程表达出来,避免了层层嵌套的回调函数。

    /* 
    2.1. 回调地狱
     */
    doSomething(function (result) {
      doSomethingElse(result, function (newResult) {
        doThirdThing(newResult, function (finalResult) {
          console.log('Got the final result: ' + finalResult)
        }, failureCallback)
      }, failureCallback)
    }, failureCallback)

    /* 
    2.2. 使用promise的链式调用解决回调地狱
     */
    doSomething().then(function (result) {//编码:上--下
      return doSomethingElse(result)
    })
      .then(function (newResult) {
        return doThirdThing(newResult)
      })
      .then(function (finalResult) {
        console.log('Got the final result: ' + finalResult)
      })
      .catch(failureCallback)//异常传透

    /* 
    2.3. async/await: 回调地狱的终极解决方案
     */
    async function request () {
      try {
        const result = await doSomething()//同步代码
        const newResult = await doSomethingElse(result)
        const finalResult = await doThirdThing(newResult)
        console.log('Got the final result: ' + finalResult)
      } catch (error) {
        failureCallback(error)
      }

    }

Promise对象有以下特点

(1)对象的状态不受外界影响。只有异步操作的结果,可以决定当前是哪一种状态,有三种状态pending(进行中)、fulfilled(已成功)和rejected(已失败)。

(2)一旦状态改变,就不会再变,任何时候都可以得到这个结果。Promise对象的状态改变,只有两种可能:从pending变为fulfilled和从pending变为rejected。如果改变已经发生了,你再对Promise对象添加回调函数,也会立即得到这个结果。

(3)Promise也有一些缺点。首先,无法取消Promise,一旦新建它就会立即执行,无法中途取消。其次,如果不设置回调函数,Promise内部抛出的错误,不会反应到外部。第三,当处于pending状态时,无法得知目前进展到哪一个阶段(刚刚开始还是即将完成)。

    // **如何改变promise的状态
    //resolve/reject/抛出异常
    const p = new Promise((resolve, reject) => {
      // resolve(1)//成功 1
      // reject(2)//失败 2
      // throw new Error('出错了')//失败 Error: 出错了
      throw 3//失败 3
    })
    p.then(
      value => { console.log('成功', value) },
      reason => { console.log('失败', reason) }
    )

1.2 基本用法

Promise对象是一个构造函数,用来生成Promise实例。

Promise构造函数接受一个函数作为参数,该函数的两个参数分别是resolvereject

  • resolve函数的作用是,将Promise对象的状态从“未完成”变为“成功”(即从 pending 变为 resolved),在异步操作成功时调用,并将异步操作的结果,作为参数传递出去。参数除了正常的值以外,还可能是另一个 Promise 实例
  • reject函数的作用是,将Promise对象的状态从“未完成”变为“失败”(即从 pending 变为 rejected),在异步操作失败时调用,并将异步操作报出的错误,作为参数传递出去。参数通常是Error对象的实例,表示抛出的错误。
const promise = new Promise(function(resolve, reject) {
  // ... some code
  if (/* 异步操作成功 */){
    resolve(value);
  } else {
    reject(error);
  }
});

//p1的状态决定了p2的状态。如果p1的状态是pending,那么p2的回调函数就会等待p1的状态改变;如果p1的状态已经是resolved或者rejected,那么p2的回调函数将会立刻执行。
const p1 = new Promise(function (resolve, reject) {
  // ...
});
const p2 = new Promise(function (resolve, reject) {
  // ...
  resolve(p1);//参数是另一个 Promise 实例
})

1.3 运行流程

7d406eac0d3028d74b9aa78f8e63580f.png

2 Promise.prototype.then()

2.1基本用法

Promise 实例具有then方法,它的作用是为 Promise 实例添加状态改变时的回调函数

第一个回调函数是Promise对象的状态变为resolved时调用,第二个回调函数是Promise对象的状态变为rejected时调用。这两个函数都是可选的,不一定要提供。它们都接受Promise对象传出的值作为参数。

then方法返回的是一个新的Promise实例。因此可以采用链式写法,指定一组按照次序调用的回调函数。这时,前一个回调函数,有可能返回的还是一个Promise对象(即有异步操作),这时后一个回调函数,就会等待Promise对象的状态发生变化,才会被调用。

    // 创建promise对象
    const p = new Promise((resolve, reject) => {//执行器函数
      setTimeout(() => {// 执行异步操作
        const time = new Date()
        if (time % 2 === 1) {
          resolve('成功的数据')// 成功
        } else {
          reject('失败的数据')// 失败
        }
      }, 1000)
    })

    // 指定成功和失败的回调函数
    p.then(
      value => {//onResolved函数
        console.log('收到', value)
      },
      reason => {//onRejected函数
        console.log('收到', reason)
      }
    )

//一般来说,不要在then()方法里面定义 Reject 状态的回调函数(即then的第二个参数),总是使用catch方法。
promise
  .then(function(data) {
    // success
  }, function(err) {
    // error
  });
 
// good
promise
  .then(function(data) { //cb
    // success
  })
  .catch(function(err) {//第二种写法可以捕获前面then方法执行中的错误,也更接近同步的写法(try/catch)
    // error
  });

getJSON("/posts.json").then(function(json) {
  return json.post;
}).then(function(post) {//第一个回调函数完成以后,会将返回结果作为参数,传入第二个回调函数。
  // ...
});

2.2 执行顺序 

excutor函数是同步的,then()是同步的,then中的回调函数是异步的

let promise = new Promise(function(resolve, reject) {
  console.log('Promise');//Promise 新建后就会立即执行
  resolve();
});
promise.then(function() {
  console.log('resolved.');//then方法指定的回调函数,将在当前脚本所有同步任务执行完才会执行,所以resolved最后输出。
});
console.log('Hi!');
// Promise
// Hi!
// resolved

new Promise((resolve, reject) => {
  resolve(1);
  console.log(2);
}).then(r => {
  console.log(r);
});
// 2
// 1

new Promise((resolve, reject) => {
  return resolve(1);//调用resolve或reject以后,Promise 的使命就完成了,后继操作应该放到then方法里面
  // return后面的语句不会执行
  console.log(2);
}).then(function(val) {
    console.log(val);
});
// 1

const promise = new Promise(function(resolve, reject) {
  resolve('ok');
  throw new Error('test');//在resolve语句后面,再抛出错误,不会被捕获。因为 Promise 的状态一旦改变,就永久保持该状态,不会再变了。
});
promise
  .then(function(value) { console.log(value) })
  .catch(function(error) { console.log(error) });
// ok
 
const promise = new Promise(function (resolve, reject) {
  resolve('ok');
  setTimeout(function () { throw new Error('test') }, 0)
});
promise.then(function (value) { console.log(value) });
// ok
// Uncaught Error: test:这个错误是在 Promise 函数体外抛出的,会冒泡到最外层,成了未捕获的错误

    // **改变promise状态和指定回调函数谁先谁后?
    // 定义回调并保存,后改变状态(指定数据) ,再异步执行回调函数
    new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(11)
      }, 1000)
    }).then(
      value => { console.log('成功', value) },
      reason => { console.log('失败', reason) }
    )

    // 先改变状态(指定数据),后定义回调,再异步执行回调函数
    new Promise((resolve, reject) => {//同步
      console.log('excutor')
      resolve(22)
    }).then(//同步
      value => { console.log('成功', value) },//后
      reason => { console.log('失败', reason) }
    )
    console.log('-------------------')//先:value/reason回调异步的

2.3 注意

  • Promise.then()返回的新promise的结果由什么决定? then()指定的回调函数执行的结果决定!
    new Promise((resolve, reject) => {
      resolve(1)
      // rejected(555)//'onRejected1'-->'onResolved2'
    }).then(
      value => {
        console.log('onResolved1', value)
        // 成功(3)
        //undefined
        // return 2//返回非promise值,变为resolved
        // return Promise.resolve(3)//返回promise值,由promise的结果决定
        // 失败(2)
        // return Promise.reject(4)
        throw 5//抛出异常,变为rejected
      },
      reason => {
        console.log('onRejected1', reason)
      }
    ).then(
      value => {
        console.log('onResolved2', value)
      },
      reason => {
        console.log('onRejected2', reason)
      }
    )
  • promise通过then的链式调用串联多个任务 。同步直接return,异步用new Promise处理
    new Promise((resolve, reject) => {
      setTimeout(() => {
        console.log('异步任务1')
        resolve(1)
      }, 1000)
    }).then(
      value => {
        console.log('任务1的结果', value)
        console.log('同步任务2')
        return 2
      }
    ).then(
      value => {
        console.log('任务2的结果', value)
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            console.log('异步任务3')
            resolve(3)
          }, 1000)
        })
      }
    ).then(
      value => {
        console.log('任务3的结果', value)
      }
    )

3 Promise.prototype.catch()

3.1 基本用法

Promise.prototype.catch()方法是.then(null, rejection).then(undefined, rejection)的别名,用于指定发生错误时的回调函数

catch()方法返回的还是一个 Promise 对象,因此后面还可以接着调用then()方法。

p.then((val) => console.log('fulfilled:', val))
  .catch((err) => console.log('rejected', err));
// 等同于
p.then((val) => console.log('fulfilled:', val))
  .then(null, (err) => console.log("rejected:", err));

3.2 注意 

  • Promise 对象的错误具有“冒泡”性质,会一直向后传递,直到被捕获为止。也就是说,错误总是会被下一个catch语句捕获。then()方法指定的回调函数,如果运行中抛出错误,也会被catch()方法捕获
const promise = new Promise(function(resolve, reject) {
  throw new Error('test');
});
promise.catch(function(error) {
  console.log(error);
});
// Error: test:promise抛出一个错误,就被catch()方法指定的回调函数捕获

// 等同于写法一
const promise = new Promise(function(resolve, reject) {
  try {
    throw new Error('test');
  } catch(e) {
    reject(e);
  }
});
promise.catch(function(error) {
  console.log(error);
});

// 等同于写法二
const promise = new Promise(function(resolve, reject) {
  reject(new Error('test'));//reject()方法的作用,等同于抛出错误
});
promise.catch(function(error) {
  console.log(error);
});

getJSON('/post/1.json').then(function(post) {//成功
  return getJSON(post.commentURL);
}).then(function(comments) {
  // some code
}).catch(function(error) {//失败
  // 处理前面三个Promise产生的错误:三个 Promise 对象:一个由getJSON()产生,两个由then()产生。
});

最终的.catch相当于简写

  • 如果没有使用catch()方法指定错误处理的回调函数,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:Promise 内部的错误不会影响到 Promise 外部的代码

const someAsyncThing = function() {
  return new Promise(function(resolve, reject) {
    // 下面一行会报错,因为x没有声明
    resolve(x + 2);
  });
};
someAsyncThing()
.catch(function(error) {//如果没有报错,则会跳过catch()方法
  console.log('oh no', error);
})
.then(function() {
  console.log('carry on');
});
// oh no [ReferenceError: x is not defined]
// carry on

Promise.resolve()
.catch(function(error) {//因为没有报错,跳过了catch()方法,直接执行后面的then()方法
  console.log('oh no', error);
})
.then(function() {
  console.log('carry on');
});
// carry on
  • catch()方法之中,还能再抛出错误。如果想要中断,可以通过return new Promise(()=>{})返回一个pending状态的promise
const someAsyncThing = function() {
  return new Promise(function(resolve, reject) {
    // 下面一行会报错,因为x没有声明
    resolve(x + 2);
  });
};
someAsyncThing().then(function() {
  return someOtherAsyncThing();
}).catch(function(error) {//catch()方法抛出一个错误,因为后面没有别的catch()方法了,导致这个错误不会被捕获,也不会传递到外层
  console.log('oh no', error);
  // 下面一行会报错,因为 y 没有声明
  y + 2;
}).then(function() {
  console.log('carry on');
});
// oh no [ReferenceError: x is not defined]

someAsyncThing().then(function() {
  return someOtherAsyncThing();
}).catch(function(error) {
  console.log('oh no', error);
  // 下面一行会报错,因为y没有声明
  y + 2;
}).catch(function(error) {//用来捕获前一个catch()方法抛出的错误
  console.log('carry on', error);
});
// oh no [ReferenceError: x is not defined]
// carry on [ReferenceError: y is not defined]

fb1b9dfd3ec609e1298da3a4ddd92f7e.png

4 Promise.prototype.finally()

finally()方法用于指定不管 Promise 对象最后状态如何,都会执行的操作。finally方法的回调函数不接受任何参数.。finally方法总是会返回原来的值

promise
.then(result => {···})
.catch(error => {···})
.finally(() => {···});

// resolve 的值是 undefined
Promise.resolve(2).then(() => {}, () => {})
// resolve 的值是 2
Promise.resolve(2).finally(() => {})
// reject 的值是 undefined
Promise.reject(3).then(() => {}, () => {})
// reject 的值是 3
Promise.reject(3).finally(() => {})

//finally本质上是then方法的特例。
promise
.finally(() => {
  // 语句
});
// 等同于
promise
.then(
  result => {
    return result;
  },
  error => {
    throw error;
  }
);

server.listen(port)
  .then(function () {
    // ...
  })
  .finally(server.stop);//关掉服务器

5 Promise.all()

5.1 基本用法

Promise.all()方法用于将多个 Promise 实例包装成一个新的 Promise 实例。

参数可以不是数组,但必须具有 Iterator 接口,且返回的每个成员都是 Promise 实例。如果不是,就会先调用下面讲到的Promise.resolve方法,将参数转为 Promise 实例,再进一步处理。

p的状态由p1p2p3决定,分成两种情况。

(1)只有p1p2p3的状态都变成fulfilledp的状态才会变成fulfilled,此时p1p2p3返回值组成一个数组,传递给p的回调函数。

(2)只要p1p2p3之中有一个被rejectedp的状态就变成rejected,此时第一个被reject的实例的返回值,会传递给p的回调函数。

const p = Promise.all([p1, p2, p3]);

// 生成一个Promise对象的数组
const promises = [2, 3, 5, 7, 11, 13].map(function (id) {
  return getJSON('/post/' + id + ".json");
});
Promise.all(promises).then(function (posts) {//只有这 6 个实例的状态都变成fulfilled,或者其中有一个变为rejected,才会调用Promise.all方法后面的回调函数。
  // ...
}).catch(function(reason){
  // ...
});

    // const pAll = Promise.all([p1, p2, p3])//3
    const pAll = Promise.all([p1, p2])//[1,2]
    pAll.then(
      values => {
        console.log('成功', values)
      },
      reason => {
        console.log('失败', reason)
      }
    )

5.2 注意

  • 如果作为参数的 Promise 实例,自己定义了catch方法,那么它一旦被rejected,并不会触发Promise.all()catch方法。
  • 如果p2没有自己的catch方法,就会调用Promise.all()catch方法。
const p1 = new Promise((resolve, reject) => {
  resolve('hello');
})
.then(result => result)
.catch(e => e);
const p2 = new Promise((resolve, reject) => {
  throw new Error('报错了');//p2首先会rejected,但是p2有自己的catch方法
})
.then(result => result)
.catch(e => e);//执行完catch方法后,也会变成resolved
Promise.all([p1, p2])
.then(result => console.log(result))
.catch(e => console.log(e));
// ["hello", Error: 报错了]

const p1 = new Promise((resolve, reject) => {
  resolve('hello');
})
.then(result => result);
const p2 = new Promise((resolve, reject) => {
  throw new Error('报错了');
})
.then(result => result);
Promise.all([p1, p2])
.then(result => console.log(result))
.catch(e => console.log(e));
// Error: 报错了

6 Promise.race()

Promise.race()方法同样是将多个 Promise 实例,包装成一个新的 Promise 实例。Promise.race()方法的参数Promise.all()方法一样。

只要p1p2p3之中有一个实例率先改变状态,p的状态就跟着改变。那个率先改变的 Promise 实例的返回值,就传递p的回调函数。

const p = Promise.race([p1, p2, p3]);

//如果指定时间内没有获得结果,就将 Promise 的状态变为reject,否则变为resolve。
const p = Promise.race([
  fetch('/resource-that-may-take-a-while'),
  new Promise(function (resolve, reject) {
    setTimeout(() => reject(new Error('request timeout')), 5000)
  })
]);
p
.then(console.log)
.catch(console.error);

    // const pRace = Promise.race([p1, p2, p3])//1
    const pRace = Promise.race([p3, p2])//3
    pRace.then(
      values => {
        console.log('成功', values)
      },
      reason => {
        console.log('失败', reason)
      }
    )

7 Promise.allSettled()

有时候,我们希望等到一组异步操作都结束了,不管每一个操作是成功还是失败,再进行下一步操作。只有等到参数数组的所有 Promise 对象都发生状态变更(不管是fulfilled还是rejected),返回的 Promise 对象才会发生状态变更。

Promise.allSettled()方法接受一个数组作为参数,数组的每个成员都是一个 Promise 对象,并返回一个新的 Promise 对象。该方法返回的新的 Promise 实例,一旦发生状态变更,状态总是fulfilled,不会变成rejected。状态变成fulfilled后,它的回调函数会接收到一个数组作为参数,该数组的每个成员对应前面数组的每个 Promise 对象。results的每个成员是一个对象,对象的格式是固定的,对应异步操作的结果。

//Promise.all()方法只适合所有异步操作都成功的情况,但是只要有一个请求失败,它就会报错,而不管另外的请求是否结束。
const urls = [url_1, url_2, url_3];
const requests = urls.map(x => fetch(x));
try {
  await Promise.all(requests);
  console.log('所有请求都成功。');
} catch {
  console.log('至少一个请求失败,其他请求可能还没结束。');
}

const promises = [
  fetch('/api-1'),
  fetch('/api-2'),
  fetch('/api-3'),
];
await Promise.allSettled(promises);
removeLoadingIndicator();//只有等到这三个请求都结束了(不管请求成功还是失败),removeLoadingIndicator()才会执行

const resolved = Promise.resolve(42);
const rejected = Promise.reject(-1);
const allSettledPromise = Promise.allSettled([resolved, rejected]);
allSettledPromise.then(function (results) {//参数是数组results
  console.log(results);
});
// [
//    { status: 'fulfilled', value: 42 },//异步操作成功时
//    { status: 'rejected', reason: -1 }// 异步操作失败时
// ]

const promises = [ fetch('index.html'), fetch('https://does-not-exist/') ];
const results = await Promise.allSettled(promises);
// 过滤出成功的请求
const successfulPromises = results.filter(p => p.status === 'fulfilled');
// 过滤出失败的请求,并输出原因
const errors = results
  .filter(p => p.status === 'rejected')
  .map(p => p.reason);

8 Promise.any()

8.1 基本用法

该方法接受一组 Promise 实例作为参数,包装成一个新的 Promise 实例返回。只要参数实例有一个变成fulfilled状态,包装实例就会变成fulfilled状态;如果所有参数实例都变成rejected状态,包装实例就会变成rejected状态。

Promise.any([
  fetch('https://v8.dev/').then(() => 'home'),
  fetch('https://v8.dev/blog').then(() => 'blog'),
  fetch('https://v8.dev/docs').then(() => 'docs')
]).then((first) => {  // 只要有一个 fetch() 请求成功
  console.log(first);
}).catch((error) => { // 所有三个 fetch() 全部请求失败
  console.log(error);
});

//Promise()与await命令结合使用
const promises = [
  fetch('/endpoint-a').then(() => 'a'),
  fetch('/endpoint-b').then(() => 'b'),
  fetch('/endpoint-c').then(() => 'c'),
];
try {
  const first = await Promise.any(promises);
  console.log(first);
} catch (error) {
  console.log(error);
}

8.2 注意 

Promise.any()抛出的错误,不是一个一般的 Error 错误对象,而是一个 AggregateError 实例。它相当于一个数组,每个成员对应一个被rejected的操作所抛出的错误。

// new AggregateError() extends Array
const err = new AggregateError();
err.push(new Error("first error"));
err.push(new Error("second error"));
// ...
throw err;

var resolved = Promise.resolve(42);
var rejected = Promise.reject(-1);
var alsoRejected = Promise.reject(Infinity);
Promise.any([resolved, rejected, alsoRejected]).then(function (result) {
  console.log(result); // 42
});
Promise.any([rejected, alsoRejected]).catch(function (results) {
  console.log(results); // [-1, Infinity]
});

9 Promise.resolve()

 有时需要将现有对象转为 Promise 对象Promise.resolve()方法就起到这个作用。

const jsPromise = Promise.resolve($.ajax('/whatever.json'));

Promise.resolve('foo')
// 等价于
new Promise(resolve => resolve('foo'))

    const p1 = new Promise((resolve, reject) => {
      resolve(1)
    })
    const p2 = Promise.resolve(2)
    const p3 = Promise.reject(3)
    p1.then(value => { console.log(value) })//1
    p2.then(value => { console.log(value) })//2
    p3.catch(reason => { console.log(reason) })//3

Promise.resolve()方法的参数分成四种情况。

(1)参数是一个 Promise 实例

如果参数是 Promise 实例,那么Promise.resolve不做任何修改、原封不动地返回这个实例。

(2)参数是一个thenable对象

thenable对象指的是具有then方法的对象Promise.resolve()方法会将这个对象转为 Promise 对象,然后就立即执行thenable对象的then()方法。

let thenable = {
  then: function(resolve, reject) {//then()方法执行后,对象p1的状态就变为resolved
    resolve(42);
  }
};
let p1 = Promise.resolve(thenable);
p1.then(function (value) {
  console.log(value);  // 42
});

(3)参数不是具有then()方法的对象,或根本就不是对象

如果参数是一个原始值,或者是一个不具有then()方法的对象,则Promise.resolve()方法返回一个新的 Promise 对象,状态为resolved

const p = Promise.resolve('Hello');//字符串Hello不属于异步操作(判断方法是字符串对象不具有 then 方法)
p.then(function (s) {
  console.log(s)
});
// Hello

(4)不带有任何参数

不带参数,直接返回一个resolved状态的 Promise 对象

立即resolve()的 Promise 对象,是在本轮“事件循环”(event loop)的结束时执行

const p = Promise.resolve();
p.then(function () {
  // ...
});

setTimeout(function () {//在下一轮“事件循环”开始时执行
  console.log('three');
}, 0);
Promise.resolve().then(function () {//在本轮“事件循环”结束时执行
  console.log('two');
});
console.log('one');//立即执行
// one
// two
// three

10 Promise.reject()

Promise.reject(reason)方法也会返回一个新的 Promise 实例,该实例的状态为rejected

Promise.reject()方法的参数,会原封不动地作为reject的理由,变成后续方法的参数

const p = Promise.reject('出错了');
// 等同于
const p = new Promise((resolve, reject) => reject('出错了'))
p.then(null, function (s) {
  console.log(s)
});// 出错了

Promise.reject('出错了')
.catch(e => {
  console.log(e === '出错了')
})// true

11 Promise.try()

如果f是同步函数,那么它会在本轮事件循环的末尾执行。函数f是同步的,但是用 Promise 包装了以后,就变成异步执行了。

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

//让同步函数同步执行,异步函数异步执行
//第一种
const f = () => console.log('now');
(async () => f())();//同步:async函数,是一个立即执行的匿名函数
console.log('next');
// now
// next

(async () => f())()//异步:async () => f()会吃掉f()抛出的错误。所以,如果想捕获错误,要使用promise.catch方法。
.then(...)
.catch(...)

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

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

Promise.try(() => database.users.get({id: userId}))
  .then(...)
  .catch(...)//统一用promise.catch()捕获所有同步和异步的错误。
// next

12 应用

  • 加载图片

我们可以将图片的加载写成一个Promise,一旦加载完成,Promise的状态就发生变化。

function loadImageAsync(url) {
  return new Promise(function(resolve, reject) {
    const image = new Image();
    image.onload = function() {
      resolve(image);//加载成功,就调用resolve方法
    };
    image.onerror = function() {
      reject(new Error('Could not load image at ' + url));//加载失败,就调用reject方法
    };
    image.src = url;
  });
}
  • Generator 函数与 Promise 的结合

  •  Promise对象实现的 Ajax 操作
const getJSON = function(url) {
  const promise = new Promise(function(resolve, reject){
    const handler = function() {
      if (this.readyState !== 4) {
        return;
      }
      if (this.status === 200) {
        resolve(this.response);//resolv参数
      } else {
        reject(new Error(this.statusText));//reject参数
      }
    };
    const client = new XMLHttpRequest();
    client.open("GET", url);
    client.onreadystatechange = handler;
    client.responseType = "json";
    client.setRequestHeader("Accept", "application/json");
    client.send();
  });
  return promise;
};
getJSON("/posts.json").then(function(json) {
  console.log('Contents: ' + json);
}, function(error) {
  console.error('出错了', error);
});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值