Skip to content

Instantly share code, notes, and snippets.

@jigewxy
Created February 14, 2018 17:26
Show Gist options
  • Save jigewxy/8cfe94169abd4174288d0fc2e13bada1 to your computer and use it in GitHub Desktop.
Save jigewxy/8cfe94169abd4174288d0fc2e13bada1 to your computer and use it in GitHub Desktop.
Async method - promise.js
const fs = require('fs');
const Promise = require('promise');
const assert = require('assert');
/*
var p1 = new Promise(function(reject, resolve){
//let result= fs.readFileSync('./index.html');
let result= fs.readFileSync('./main.html');
if(result)
resolve(result);
else
reject("error");
});
p1.then(function(data){
console.log("p1 resolved");
}, function(err){
console.log(err);
});*/
var p3 = Promise.reject("manual reject"); //return a rejected promise
var p4 = Promise.resolve("manual resolve");
p3.then((data)=>console.log(data), (err)=>console.log(err));
var read = Promise.denodeify(fs.readFile);
var fl = ['./main.html', './index.html'];
fl.forEach(function(index,i){
read(index).then(function(data){
// console.log(data.toString());
console.log("denodeify demo");
})
});
Promise.all([Promise.resolve('a'), Promise.reject('b'), Promise.resolve('c')])
.then(function (res) {
console.log(res);
assert.strictEqual(res[0], 'e');
assert(res[1] === 'b');
assert(res[2] === 'c');
assert(false);
});
// Promise() doesn't work with async function with callback unless we denodeify them.
/*
var p2 = new Promise(function(reject, resolve){
fl.forEach(function(index, i){
let result = fs.readFile(index, (err, data)=>{
if(err)
reject(err);
else
{
console.log(i);
if(i==(fl.length-1))
resolve("async read completed");
}
});
});
});
p2.then(function(data){
console.log("p2 resolved");
}, function(err){
console.log(err);
});
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment