function want() {
console.log('这是你想要执行的代码');
}
function fn(want) {
// console.log('这里表示执行了一大堆各种代码');
// 返回Promise对象
return new Promise(function (resolve, reject) {
if (typeof want === 'function') {
resolve(want);
} else {
reject('TypeError: ' + want + '不是一个函数')
}
}).then(function (want) {
want();
}).catch(function (err) {
console.log(err);
})
}
fn(want)
数据怎么传递
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;
});
封装一个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)
});