其他分享
首页 > 其他分享> > [JS]promises对象

[JS]promises对象

作者:互联网

目录

什么是promise

Promise 是一个对象,它代表了一个异步
操作的最终完成或者失败。

Promise 构造函数包含一个参数和一个带有 resolve(解析)和 reject(拒绝)两个参数的回调。 在回调中执行一些操作(例如异步),如果一切都正常,则调用 resolve,否则调用 reject。

怎么使用

var promise = new Promise(function(resolve, reject) {
  // do a thing, possibly async, then…

  if (/* everything turned out fine */) {
    resolve("ok!");
  }
  else {
    reject(Error("failed"));
  }
});
promise.then(function(result) {
  console.log(result); // "ok!"
}, function(err) {
  console.log(err); // Error:"failed"
});

XMLHttpRequest 执行 promise

function get(url) {
  // Return a new promise.
  return new Promise(function(resolve, reject) {
    // Do the usual XHR stuff
    var req = new XMLHttpRequest();
    req.open('GET', url);

    req.onload = function() {
      // This is called even on 404 etc
      // so check the status
      if (req.status == 200) {
        // Resolve the promise with the response text
        resolve(req.response);
      }
      else {
        // Otherwise reject with the status text
        // which will hopefully be a meaningful error
        reject(Error(req.statusText));
      }
    };

    // Handle network errors
    req.onerror = function() {
      reject(Error("Network Error"));
    };

    // Make the request
    req.send();
  });
}

简写,使用then

一个用于成功,一个用于失败(即promise 执行和拒绝):

get('story.json').then(function(response) {
  console.log("Success!", response);
}, function(error) {
  console.error("Failed!", error);
})

换成catch

get('story.json').then(function(response) {
  console.log("Success!", response);
}).catch(function(error) {
  console.log("Failed!", error);
})

换成finally

get('story.json').then(function(response) {
  console.log("Success!", response);
}).catch(function(error) {
  console.log("Failed!", error);
})

需要注意

执行程序应该只调用一个解析或一个拒绝。任何状态的改变都是最终的。
所有进一步的操作和拒绝将被被忽略:

let promise = new Promise(function(resolve, reject) {
  resolve("done");

  reject(new Error("…")); // ignored
  setTimeout(() => resolve("…")); // ignored
});

总结

使用了promise,在异步执行的流程中,把执行代码和处理结果的代码清晰地分离了。简单的写了一个promise的使用,大家可以仔细看下底下参考链接,想具体学习可以看阮一峰老师的ES6课程。

参考链接

https://developers.google.com/web/fundamentals/primers/promises?hl=zh-cn#top_of_page
https://www.liaoxuefeng.com/wiki/1022910821149312/1023024413276544
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Using_promises
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise
https://es6.ruanyifeng.com/#docs/promise

标签:function,promises,resolve,console,对象,req,JS,promise,reject
来源: https://blog.csdn.net/u013716535/article/details/105863013