<!DOCTYPE html>
<html lang="en">
<head>
<Meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
// then参数中的函数返回值
function queryData(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState != 4) return;
if (xhr.readyState == 4 && xhr.status == 200) {
// 处理正常的情况
resolve(xhr.responseText);
} else {
// 处理异常情况
reject('服务器错误');
}
};
xhr.open('get', url);
xhr.send(null);
});
}
queryData('http://localhost:3000/data')
.then(function(data) {
return queryData('http://localhost:3000/data1');
})
.then(function(data) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(123);
}, 1000)
});
})
.then(function(data) {
return 'hello';
})
.then(function(data) {
console.log(data)
})
</script>
<script>
var p = new Promise(function(resolve, reject) {
resolve('sd')
// return 'qw';
});
p.then(function(data) {
// console.log(data);
// resolve('sd'); //.then 内部是没有resolve方法的,会报错
return 'qw'; //.then 内部return的内容会作为参数传递给下一个then;猜测
//promise内的resolve也是通过return来传递数据的,只是处理成功才会触发
//resolve
})
.then(function(data) {
console.log(data);
return 2;
})
.then(function(data) {
console.log(data);
})
</script>
</body>
</html>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。