68 lines
1.5 KiB
JavaScript
68 lines
1.5 KiB
JavaScript
import { square, diag } from './a.js';
|
||
console.log(square(11)); // 121
|
||
console.log(diag(4, 3)); // 5
|
||
|
||
|
||
// promise 构造函数接受一个函数作为参数,该函数的两个参数分别是resolve,reject
|
||
// 成功时调用resolve函数,失败时调用reject函数
|
||
|
||
// const promise = new Promise(function(resolve, reject) {
|
||
// // ... some code
|
||
|
||
// if (/* 异步操作成功 */){
|
||
// resolve(value);
|
||
// } else {
|
||
// reject(error);
|
||
// }
|
||
// });
|
||
|
||
|
||
// promise.then(function(value) {
|
||
// // success
|
||
// }, function(error) {
|
||
// // failure
|
||
// })
|
||
|
||
|
||
let promise = new Promise(function(resolve, reject) {
|
||
console.log('Promise');
|
||
resolve();
|
||
});
|
||
|
||
promise.then(function() {
|
||
console.log('resolved.');
|
||
});
|
||
|
||
console.log('Hi!');
|
||
|
||
|
||
|
||
const getJSON = function(url) {
|
||
const promise = new Promise(function(resolve, reject){
|
||
const handler = function() {
|
||
if (this.readyState !== 4) {
|
||
return;
|
||
}
|
||
if (this.status === 200) {
|
||
resolve(this.response);
|
||
} else {
|
||
reject(new Error(this.statusText));
|
||
}
|
||
};
|
||
const client = new XMLHttpRequest();
|
||
client.open("GET", url);
|
||
client.onreadystatechange = handler;
|
||
client.responseType = "json";
|
||
client.setRequestHeader("Accept", "application/json");
|
||
client.send();
|
||
|
||
});
|
||
|
||
return promise;
|
||
};
|
||
|
||
getJSON("/posts.json").then(function(json) {
|
||
console.log('Contents: ' + json);
|
||
}, function(error) {
|
||
console.error('出错了', error);
|
||
}); |