Created
February 14, 2018 17:26
-
-
Save jigewxy/8cfe94169abd4174288d0fc2e13bada1 to your computer and use it in GitHub Desktop.
Async method - promise.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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