Skip to content

Instantly share code, notes, and snippets.

@linkerlin
Created October 25, 2018 05:19
Show Gist options
  • Save linkerlin/7c954ecbb24d82c4bc15e6ae067005f3 to your computer and use it in GitHub Desktop.
Save linkerlin/7c954ecbb24d82c4bc15e6ae067005f3 to your computer and use it in GitHub Desktop.
关于Promise的例子
function 获取网络资源(网址) {
return new Promise((解决, 拒绝)=> {
var 请求 = new XMLHttpRequest();
请求.open('GET', 网址, true);
请求.onload = 括弧=> {
if (请求.status === 200) {
解决(请求.responseText);
} else {
拒绝(new Error(请求.statusText));
}
};
请求.onerror = 括弧=> {
拒绝(new Error(请求.statusText));
};
请求.send();
});
}
// 运行示例
var 网址 = "http://httpbin.org/get";
获取网络资源(网址).then(值=>{
throw "丢你老母"
console.log("返回值:<br/>"+值);
}).catch(错误=>{
console.error("出错了:"+错误);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment