promise
// 需求:封装一个方法,给一个读取文件的路径,方法能给我们返回文件内容
const fs = require('fs') const path = require('path') // callback回调:第一个参数错误结果,第二个参数读取的文件内容 function getFileByPath(fpath, callback) { fs.readFile(fpath, 'utf-8', (err, dataStr) => { if (err) return callback(err) callback(null, dataStr) }) } getFileByPath(path.join(__dirname, './package.json'), (err, dataStr) => { if (err) return console.log(err.message) //console.log(dataStr) console.log(JSON.parse(dataStr).name) })
function test(resolve, reject) { var timeOut = Math.random() * 2; console.log('set timeout to: ' + timeOut + ' seconds.'); setTimeout(function () { if (timeOut < 1) { console.log('call resolve()...'); resolve('200 OK'); } else { console.log('call reject()...'); reject('timeout in ' + timeOut + ' seconds.'); } }, timeOut * 1000); } // var p1 = new Promise(test); // var p2 = p1.then(function (result) { // console.log('成功:' + result); // }); // var p3 = p2.catch(function (reason) { // console.log('失败:' + reason); // }); new Promise(test).then(res => console.log("succ")).catch(err => console.log("failed"))
posted on 2019-10-03 19:03 wenbin_ouyang 阅读(209) 评论(0) 编辑 收藏 举报