promise
用来处理异步方法
创建Promise对象后,会有两个返回值,分别是resolve、reject表示成功与失败。如果成功,则调用resolve(data),data中可以将成功的值传递,如果是失败,则调用reject(error),将失败的内容传递。
promise有一个then的返回值,在执行完promise的function之后,会通过then方法,将promise的返回值输出。
const fs = require("fs")
const promise = new Promise(function (resolve, reject) {
fs.readFile("./1.txt","utf-8",function (error, data) {
if (error){
reject(error)
}else {
resolve(data)
}
})})
promise.then(function(data){
console.log(data)
}).catch(function (error){
console.log(error)
})
console.log("hello")
输出测试:
PS D:\nodeProject\promise> node .\1_promise.js
hello
1111
2222
修改访问路径后,测试输出如下:
PS D:\nodeProject\promise> node .\1_promise.js
hello
1111
code: 'ENOENT',
syscall: 'open',
path: 'D:\\nodeProject\\promise\\2.txt'
}
回调地狱问题举例
要求
依次读取1.txt、2.txt、3.txt
如果仅是按照顺序书写回调函数的话,回调没法确保文件读取的顺序。
const fs = require("fs")
fs.readFile("./1.txt","utf-8",function (error, data) {
if (error){
console.log(error)
}else {
console.log(data)
}
})
fs.readFile("./2.txt","utf-8",function (error, data) {
if (error){
console.log(error)
}else {
console.log(data)
}
})
fs.readFile("./3.txt","utf-8",function (error, data) {
if (error){
console.log(error)
}else {
console.log(data)
}
})
console.log("hello")
输出结果:
PS D:\nodeProject\promise> node .\1_promise.js
hello
1111
3333
2222
因此,需要在读取1.txt的回调中执行读取2.txt…
const fs = require("fs")
fs.readFile("./1.txt","utf-8",function (error, data) {
if (error){
console.log(error)
}else {
console.log(data)
fs.readFile("./2.txt","utf-8",function (error, data) {
if (error){
console.log(error)
}else {
console.log(data)
fs.readFile("./3.txt","utf-8",function (error, data) {
if (error){
console.log(error)
}else {
console.log(data)
}
})
}
})
}
})
console.log("hello")
输出结果:
PS D:\nodeProject\promise> node .\1_promise.js
hello
1111
2222
3333