function want() {
console.log('這是你想要執(zhí)行的代碼');
}
function fn(want) {
// console.log('這里表示執(zhí)行了一大堆各種代碼');
// 返回Promise對(duì)象
return new Promise(function (resolve, reject) {
if (typeof want === 'function') {
resolve(want);
} else {
reject('TypeError: ' + want + '不是一個(gè)函數(shù)')
}
}).then(function (want) {
want();
}).catch(function (err) {
console.log(err);
})
}
fn(want)
數(shù)據(jù)怎么傳遞
let fn = function (num) {
return new Promise(function (resolve, reject) {
if (typeof num === 'number') {
resolve(num);
} else {
reject('typeError');
}
});
};
fn(2).then(num => {
console.log('first:' + num);
return num + 1;
}).then(num1 => {
console.log('s:' + num1);
return num1 + 1;
}).then(num2 => {
console.log('t:' + num2);
return num2 + 1;
});
封裝一個(gè)ajax
const url = 'https://hq.tigerbrokers.com/fundamental/finance_calendar/getType/2017-02-26/2017-06-10'
function getJSON(url) {
return new Promise(function (resolve, reject) {
let XHR = new XMLHttpRequest();
XHR = open('get', url, true);
XHR = send();
XHR.onreadystatechange = function () {
if (XHR.readyState === 4) {
if (XHR.status === 200) {
try {
let response = JSON.parse(XHR.responseText);
resolve(response);
} catch (e) {
reject(e);
}
}
} else {
reject(new Error(XHR.statusText))
}
}
})
}
getJSON(url).then(resp => {
console.log(resp)
});