Promise基础语法

通过promise将普通函数变成回调函数

clike 复制代码
let promise = new Promise(function (){})

在这个函数里面可以接收两个参数

resolve 函数 在回调函数中如果调用resolve方法,promise会由pending转换为resolved

reject 函数 在回调函数中如果调用reject方法,promise会由pending转换为reject

clike 复制代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的页面</title>
    <script>      
      let promise = new Promise(function (resolve,reject){
        console.log("function invoked")
        resolve()
      })
      console.log("other code1")
    //   等待promise对象状态发生改变时才会执行的代码
      promise.then(
        function(){
            // promise转换为resolved状态时会执行的函数
            console.log("promise success")

        },
        function(){
            // promise转换为reject状态时会执行的函数
             console.log("promise fail")

        }
      )
      console.log("other code2")
    </script>
</head>
<body>
</body>
</html>

then里面是可以接收参数的

clike 复制代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的页面</title>
    <script>      
      let promise = new Promise(function (resolve,reject){
        console.log("function invoked")
        reject("haha")
        // resolve()
      })
      console.log("other code1")
    //   等待promise对象状态发生改变时才会执行的代码
      promise.then(
        function(){
            // promise转换为resolved状态时会执行的函数
            console.log("promise success")
 
        },
        function(data){
            // promise转换为reject状态时会执行的函数
             console.log("promise fail   " + data)

        }
      )
      console.log("other code2")
    </script>
</head>
<body>
</body>
</html>
相关推荐
灵感__idea1 天前
Hello 算法:贪心的世界
前端·javascript·算法
小成202303202651 天前
Linux高级02
linux·开发语言
知行合一。。。1 天前
Python--04--数据容器(总结)
开发语言·python
咸鱼2.01 天前
【java入门到放弃】需要背诵
java·开发语言
ZK_H1 天前
嵌入式c语言——关键字其6
c语言·开发语言·计算机网络·面试·职场和发展
A.A呐1 天前
【C++第二十九章】IO流
开发语言·c++
椰猫子1 天前
Java:异常(exception)
java·开发语言
lifewange1 天前
pytest-类中测试方法、多文件批量执行
开发语言·python·pytest
GreenTea1 天前
一文搞懂Harness Engineering与Meta-Harness
前端·人工智能·后端
cmpxr_1 天前
【C】原码和补码以及环形坐标取模算法
c语言·开发语言·算法