1、Promise能解决回调地狱
代码示例:
node.js文件:
/**
* Created by 10853 on 2020/2/1.
*/
//引入模块
var express=require('express');
//创建服务器
var app=express();
app.set('View engine','ejs');
app.set('views','./');
//开启服务器并监听端口
app.listen(3000,function(){
console.log('this express server is running at http://127.0.0.1:3000 ');
})
app.get('/', function (req, res, next) {
res.render('index.ejs', {title: 'Express'});
});
app.get('/news', function (req, res, next) {
res.set('Access-Control-Allow-Origin', '*');
var id = req.query.id;
console.log('/news id='+id);
var news = {
id: id,
title: 'news title1...',
content: 'news content1...',
commentsUrl: '/comments?newsId='+id
};
res.json(news);
});
//根据前一个路由返回的Url路径,获得另一个路由地址,和查询新闻的id
app.get('/comments', function (req, res, next) {
res.set('Access-Control-Allow-Origin', '*');
console.log('/comments newsId=' + req.query.newsId);
var newsId = req.query.newsId;
var comments = [
{
id: 1,
content: 'comment content1111...',
newsId : newsId
},
{
id: 2,
content: 'comment content2222...',
newsId : newsId
}];
res.json(comments);
});
module.exports=app;
html文件:
<html ng-app='app' ng-controller='main' >
<head>
<meta charset="utf-8">
<meta name='viewport' content='width=device-width,user-scalable=no,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0'>
<script src='jq/jquery-3.4.1.js'></script>
<style>
</style>
</head>
<body >
<script>
//定义获取新闻的功能函数
function getNews(url){
let promise=new Promise((resolve,reject)=>{
let xhr=new XMLHttpRequest();
xhr.onreadystatechange=function()
{
if(xhr.readyState==4)
{
if(xhr.status==200)
{
//修改异步状态
resolve(JSON.parse(xhr.responseText));
}
}
}
xhr.open('GET',url,true);
xhr.send(null);
})
return promise;
}
getNews('http://localhost:3000/news?id=2')
.then((data)=>{
let url='http://localhost:3000'+data.commentsUrl;
//第二个路由返回数据
return getNews(url);
},()=>{})
.then((data)=>{console.log(data)},()=>{})
</script>
</body>
</html>