--------------
基礎
const p = new Promise(function(resolve,reject){
setTimeout(() => {
// let data = '數據庫中的用戶數據';
// resolve(data);
let err = '數據讀取失敗';
reject(err)
}, 1000);
});
p.then(function(value){
console.log(value);
},function(reason){
// console.log(reason);
console.error(reason);
})
----------------------
// 引入 fs 模塊
const fs = require('fs');
// 2 調用方法讀取文件
// fs.readFile('./test.md',(err,data)=>{
// // 若是 出錯 則拋出錯誤
// if(err) throw err;
// // 若是沒出錯, 則輸出內容
// console.log(data.toString());
// })
// 3 使用 Promise 封裝
const p = new Promise(function(resolve,reject){
fs.readFile('./test.m3d',(err,data)=>{
// 若是 出錯 則拋出錯誤
if(err) reject(err);
// 若是沒出錯, 則返回內容
resolve(data);
})
})
p.then(function(value){
console.log(value.toString());
},function(reason){
console.log(reason);
console.log('讀取失敗');
})
--------------------------------
封裝ajax 請求
// 接口地址: https://api.apiopen.top/getJoke
// // 1 建立對象
// const xhr = new XMLHttpRequest();
// // 2 初始化
// xhr.open("GET","https://api.apiopen.top/getJo3ke");
// // 3 發送
// xhr.send();
// // 4 綁定事件 處理響應結果
// xhr.onreadystatechange = function(){
// // 判斷狀態
// if(xhr.readyState === 4){
// // 判斷響應狀態碼 200 - 299
// if(xhr.status >= 200 && xhr.status < 300){
// // 表示成功
// console.log(xhr.response);
// }else{
// console.error(xhr.status);
// }
// }
// }
//promise 封裝
const p = new Promise((resolve,reject)=>{
// 1 建立對象
const xhr = new XMLHttpRequest();
// 2 初始化
xhr.open("GET","https://api.apiopen.top/getJoke");
// 3 發送
xhr.send();
// 4 綁定事件 處理響應結果
xhr.onreadystatechange = function(){
// 判斷狀態
if(xhr.readyState === 4){
// 判斷響應狀態碼 200 - 299
if(xhr.status >= 200 && xhr.status < 300){
// 表示成功
// console.log(xhr.response);
resolve(xhr.response)
}else{
// console.error(xhr.status);
reject(xhr.status)
}
}
}
})
// 指定回調
p.then(function(value){
console.log(value);
},function(reason){
console.error(reason);
})
-------------------------------------ajax
promise-讀取多個文數據庫
const fs = require('fs');
// fs.readFile('./test.md',(err,data1)=>{
// fs.readFile('./test2.md',(err,data2)=>{
// fs.readFile('./test3.md',(err,data3)=>{
// let result = data1 + '\r\n' + data2 + '\r\n' + data3;
// console.log(result);
// })
// })
// })
// 使用 promise 實現
const p = new Promise((resolve, reject)=>{
fs.readFile('./test.md',(err,data)=>{
resolve(data)
})
})
p.then(value=>{
return new Promise((resolve,reject)=>{
fs.readFile('./test2.md',(err,data)=>{
resolve([value,data])
})
})
}).then(value=>{
return new Promise((resolve,reject)=>{
fs.readFile('./test3.md',(err,data)=>{
value.push(data);
resolve(value);
})
})
}).then(value=>{
// console.log(value.toString());
console.log(value.join('\r\n'));
})
// console.log(value.toString());
-------------api
const p = new Promise((resolve,reject)=>{
setTimeout(() => {
// 設置 p 對象 的狀態爲失敗 並設置 失敗的值
reject("出錯了")
}, 1000);
})
// p.then(function(value){},function(reason){
// console.error(reason);
// })
p.catch(function(reason){
console.warn(reason);
})