Promise使用

来源:互联网 发布:某路口车流量数据 编辑:程序博客网 时间:2024/06/09 17:19

所谓 Promise,就是一个对象,用来传递异步操作的消息。它代表了某个未来才会知道结果的事件(通常是一个异步操作),并且这个事件提供统一的 API,可供进一步处理。

使用步骤:

  1. 创建一个Promise对象,在这个对象中进行异步请求操作,如果操作成功,则调用resolve()函数,传入参数,如果失败,则调用reject()函数。
  2. 实际使用时调用then()函数,针对resolve传入值进行进一步操作,catch()函数针对reject传入值进行操作。
  3. 实例如下
let myFirstPromise = new Promise((resolve, reject) => {  // We call resolve(...) when what we were doing asynchronously was successful, and reject(...) when it failed.  // In this example, we use setTimeout(...) to simulate async code.   // In reality, you will probably be using something like XHR or an HTML5 API.  setTimeout(function(){    resolve("Success!"); // Yay! Everything went well!  }, 250);});myFirstPromise.then((successMessage) => {  // successMessage is whatever we passed in the resolve(...) function above.  // It doesn't have to be a string, but if it is only a succeed message, it probably will be.  console.log("Yay! " + successMessage);}).catch(  // Log the rejection reason  (reason) => {      console.log('Handle rejected promise ('+reason+') here.');        });