JavaScript中promise的基本用法

来源:互联网 发布:java 网络拓扑发现 编辑:程序博客网 时间:2024/05/16 12:24

自己写的小栗子:

<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
var runAsync = function(){
var p = new Promise(function(resolve, reject){
        //做一些异步操作
        setTimeout(function(){
            console.log('执行完成');
            resolve('随便什么数据');
        }, 1000);
    });
    return p;
}
var runAsync1 = function(){
var p = new Promise(function(resolve, reject){
        //做一些异步操作
        setTimeout(function(){
            console.log('执行完成');
            resolve('随便什么数据1');
        }, 1000);
    });
    return p;
}
var runAsync2 = function(){
var p = new Promise(function(resolve, reject){
        //做一些异步操作
        setTimeout(function(){
            console.log('执行完成');
            resolve('随便什么数据2');
        }, 1000);
    });
    return p;
}
runAsync().then(function(data){
    console.log(data);
    return runAsync1() ;
}).then(function(data){
console.log(data) ;
return "xixixi" ;
}).then(function(data){
console.log(data) ;
});
</script>
</body>
</html>