Home > Web Front-end > JS Tutorial > Example of simple implementation of Javascript Promise mechanism in nodejs_node.js

Example of simple implementation of Javascript Promise mechanism in nodejs_node.js

WBOY
Release: 2016-05-16 16:28:44
Original
1557 people have browsed it

Promise/deferred is a good specification for handling asynchronous call coding. The following uses nodejs code as a class to implement a simple implementation of the promise/A specification

Copy code The code is as follows:

/**
 * Created with JetBrains WebStorm.
 * User: xuwenmin
 * Date: 14-4-1
 * Time: 上午9:54
 * To change this template use File | Settings | File Templates.
 */

var EventEmitter = require('events').EventEmitter;
var http = require('http');
var util = require('util');
//Define promise object
var Promise = function(){
// Implement inherited event class
EventEmitter.call(this);
}
//Inherit event general method
util.inherits(Promise, EventEmitter);
//The then method is the method in the promise/A specification
Promise.prototype.then = function(successHandler, errorHandler, progressHandler){
If (typeof successHandler == 'function'){
This.once('success', successHandler);
}
If (typeof errorHandler === 'function'){
This.once('error', errorHandler);
}
If (typeof progressHandler === 'function'){
This.on('process', progressHandler);
}
Return this;
}

//Define deferred object
//Contains a state and a promise object
var Deferred = function(){
This.state = 'unfulfilled';
This.promise = new Promise();
}
Deferred.prototype.resolve = function(obj){
This.state = 'fulfilled';
This.promise.emit('success', obj);
}
Deferred.prototype.reject = function(err){
This.state = 'failed';
This.promise.emit('error', err);
}
Deferred.prototype.progress = function(data){
This.promise.emit('process', data);
}

//Use an http request to apply the promise/deferred defined above

var client = function(){
var options = {
Hostname:'www.baidu.com',
Port:80,
        path:'/',
Method: 'get'
};
var deferred = new Deferred();
var req = http.request(options, function(res){
          res.setEncoding('utf-8');
      var data = '';
          res.on('data', function(chunk){
              data = chunk;
               deferred.progress(chunk);
        });
          res.on('end', function(){
              deferred.resolve(data);
        });
});
req.on('error', function(err){
         deferred.reject(err);
})
req.end();
Return deferred.promise;
}
client().then(function(data){
console.log('Request completed', data);
}, function(err){
Console.log('Access error', err);
}, function(chunk){
console.log('reading', chunk);
});

The code is saved as promise.js, which can be run under the command line. Directly enter node promise.js to see the running effect.

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