An example of a simple implementation of the Javascript Promise mechanism in nodejs
- 2020-03-30 04:32:27
- OfStack
Promise /deferred is A good specification for handling asynchronous call coding. The following nodejs code is used as A class to implement A simple implementation of the promise/A specification
/**
* Created with JetBrains WebStorm.
* User: xuwenmin
* Date: 14-4-1
* Time: In the morning 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 a promise object
var Promise = function(){
//Implement the inherited event class
EventEmitter.call(this);
}
//Inherited 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 the delay 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 is completed ', data);
}, function(err){
console.log(' Access errors ', err);
}, function(chunk){
console.log(' Is being read ', chunk);
});
Save the code as promise.js, you can run under the command line, directly enter node promise.js, you can see the effect.