基于promise.js实现nodejs的promises库

2020-06-17 06:51:35易采站长站整理

return p;
}

var o = {};
/*
asyncfoo().then(function(){
return 'Raymond';
}, o).then(function(err, name){
o.name = name;
return asyncfoo().then(asyncfoo).then(function(){
return asyncfoo().then(asyncfoo).then(function(){
return 18;
});
});
}, o).then(function(err, age){
o.age = age;
return asyncfoo().then(asyncfoo).then(function(){
return asyncfoo().then(asyncfoo).then(function(){
return 'boy';
});
}).then(function(err, sex){
return sex;
});
}).then(function(err, sex){
o.sex = sex;
return 'Hello, world!';
}).then(function(err, say){
o.say = say;
console.dir(o);
});

syncfoo().then(function(){
return 'Raymond';
}, o).then(function(err, name){
o.name = name;
return syncfoo().then(syncfoo).then(function(){
return syncfoo().then(syncfoo).then(function(){
return 18;
});
});
}, o).then(function(err, age){
o.age = age;
return asyncfoo().then(asyncfoo).then(function(){
return asyncfoo().then(asyncfoo).then(function(){
return 'boy';
});
}).then(function(err, sex){
return sex;
});
}).then(function(err, sex){
o.sex = sex;
return 'Hello, world!';
}).then(function(err, say){
o.say = say;
console.dir(o);
});
*/
function asyncfoo1(){
var p = new promise.Promise();
setTimeout(function(){
p.done(null, 'Raymond');
}, 1000);
return p;
}

function asyncfoo2(err, name){
o.name = name;
var p = new promise.Promise();
setTimeout(function(){
p.done(null, 18);
}, 1000);
return p;
}
function asyncfoo3(err, age){
o.age = age;
var p = new promise.Promise();
setTimeout(function(){
p.done(null, 'boy');
}, 1000);
return p;
}
function asyncfoo4(){
var p = new promise.Promise();
setTimeout(function(){
p.done(null, 'Hello, world!');
}, 1000);
return p;
}
promise.Promise.chain([asyncfoo1, asyncfoo2, asyncfoo3]).then(function(err, sex){
o.sex = sex;
return asyncfoo4();
}).then(function(err, say){
o.say = say;
}).then(function(){
console.dir(o);
});