javascript使用Promise對象實現非同步編程,javascriptpromise

來源:互聯網
上載者:User

javascript使用Promise對象實現非同步編程,javascriptpromise

Promise對象是CommonJS工作群組為非同步編程提供的統一介面,是ECMAScript6中提供了對Promise的原生支援,Promise就是在未來發生的事情,使用Promise可以避免回呼函數的層層嵌套,還提供了規範更加容易的對非同步作業進行控制。提供了reject,resolve,then和catch等方法。

使用PROMISE

Promise是ES6之後原生的對象,我們只需要執行個體化Promise對象就可以直接使用。
執行個體化Promise:

var promise = new Promise(function (resolve, reject) {  console.log('begin do something');  if (Math.random() * 10.0 > 5) {    console.log(" run success");    resolve();  } else {    console.log(" run failed");    reject();  }});

這裡定義了一個回調方法function(resolve,reject),如果成功了就調用resolve,失敗了就會調用reject。
Promise.prototype.then是Promise執行完之後的回調,可以用then方法分別指定resolve和reject的回調。

promise.then(function () {  console.log(' resolve from promise');}, function () {  console.log(' reject from promise');});

執行結果一:

begin do something run success resolve from promise

執行結果二:

begin do something run failed reject from promise

使用PROMISE進行網路請求

getRequest = function (url) {  var promise = new Promise(function (resolve, reject) {    var request = require('request');    request(url, function (error, respones, body) {      if (error) {        reject(error);        return;      }      if (respones.statusCode == 200) {        resolve(body)      } else {        reject(respones.status);      }    });  });  return promise;};getRequest("https://github.com/").then(function (result) {  console.log(result);}, function (error) {  console.error('error', error);});

使用Promise進行網路請求,也可以使用Promise在瀏覽上實現Ajax請求。

代碼地址:https://github.com/jjz/node

您可能感興趣的文章:
  • JavaScript非同步編程Promise模式的6個特性
  • Javascript中的非同步編程規範Promises/A詳細介紹
  • node.js中使用q.js實現api的promise化
  • NodeJS中利用Promise來封裝非同步函數
  • 舉例詳解JavaScript中Promise的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.