javascript uses Promise objects for asynchronous programming

  • 2021-01-18 06:16:14
  • OfStack

The Promise object is the standard interface for asynchronous programming provided by the CommonJS working group. It is the native support for Promise in ECMAScript6. Promise is what will happen in the future. reject,resolve,then, and catch methods are provided.

Using PROMISE

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

  }
});

There is a callback method, function(resolve,reject), which is called on success and reject on failure.
Promise.prototype.then is a callback to the execution of Promise. You can specify a callback to resolve and reject using the then method.


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

Result 1:


begin do something
 run success
 resolve from promise

Result 2:


begin do something
 run failed
 reject from promise

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

Promise is used to make network requests, or Promise is used to implement Ajax requests on browsing.

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


Related articles: