webveuje/es6/b.js
2021-03-23 10:58:10 +08:00

68 lines
1.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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);
});