Home > Web Front-end > JS Tutorial > body text

JavaScript uses Promise objects to implement asynchronous programming_javascript skills

WBOY
Release: 2016-05-16 15:12:35
Original
1159 people have browsed it

The Promise object is a unified interface provided by the CommonJS working group for asynchronous programming. It is the native support for Promise provided in ECMAScript6. Promise is what will happen in the future. Using Promise can avoid layers of nesting of callback functions and also provides The specification makes it easier to control asynchronous operations. Provides methods such as reject, resolve, then and catch.

Use PROMISE

Promise is a native object after ES6. We only need to instantiate the Promise object to use it directly.
Instantiate 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();

  }
});

Copy after login

A callback method function(resolve,reject) is defined here. If it succeeds, resolve will be called. If it fails, reject will be called.
Promise.prototype.then is the callback after Promise is executed. You can use the then method to specify the callbacks of resolve and reject respectively.

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

Execution result one:

begin do something
 run success
 resolve from promise
Copy after login

Execution result two:

begin do something
 run failed
 reject from promise
Copy after login

Use PROMISE for network requests

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);
});

Copy after login

Use Promise to make network requests, and you can also use Promise to implement Ajax requests on browsing.

Code address: https://github.com/jjz/node

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template