欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Promise对象与async函数

程序员文章站 2022-07-13 09:31:15
...

环境搭建

npm init -y
npm install --save express
  • 服务器端
//server.js
const express = require("express");
const server = express();
server.use(express.static(__dirname));
server.get("/data",function(req,res){
    const user = {
        name:"左一",
        address:"上海 "
    }
    res.json(user);
});
server.get("/name",function(req,res){
    const name = "左一";
    res.send(name);
})
server.listen("3030",function(){
    console.log("listening on *:3030");
})
  • 浏览器端
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script src="./index.js"></script>
</body>
</html>
//index.js
function getDataFromServer(){
    return fetch("/data").then(function(response){
        return response.json();
    }).then(function(user){
        console.log(user);
        return user;
    })
}
function getName(){
    return fetch("/name").then(function(response){
        return response.text();
    }).then(function(name){
        console.log(name);
        return name;
    })
}

回调函数作参数

//index.js
function getDataFromServer(callback){
    fetch("/data").then(function(response){
        return response.json();
    }).then(function(user){
        callback(user);
    })
}
function preprocessBeforeRendering(user,callback){
    const str = `${user.name}他现在在${user.address}`;
    callback(str);
}
function render(htmlString){
    document.body.innerHTML = htmlString;
}

getDataFromServer(function(user){
    preprocessBeforeRendering(user,function(htmlString){
        render(htmlString);
    })
})

Promise

new Promise().then()
//index.js
function getDataFromServer(){
    return fetch("/data").then(function(response){
        return response.json();
    }).then(function(user){
        return user;
    })
}
function preprocessBeforeRendering(user){
    return `${user.name}他现在在${user.address}`;
}
function render(htmlString){
    document.body.innerHTML = htmlString;
}

getDataFromServer()
.then(function(user){
    return preprocessBeforeRendering(user);
}).then(function(htmlString){
    render(htmlString);
})
  • fetch返回一个Promise对象
  • then(onFulflled,onRejected)
    接受两个参数,返回一个Promise对象
    • onFulfilled
      异步操作成功时调用的回调函数
      回调函数的参数是异步操作的结果
    • onRejected
      异步操作失败时调用的回调函数
      回调函数的参数是异步操作的结果
Promise.resolve().then()
//index.js
function getDataFromServer(){
    return fetch("/data").then(function(response){
        return response.json();
    }).then(function(user){
        return user;
    })
}
function preprocessBeforeRendering(user){
    return `${user.name}他现在在${user.address}`;
}
function render(htmlString){
    document.body.innerHTML = htmlString;
}
Promise.resolve()
.then(getDataFromServer)
.then(preprocessBeforeRendering)
.then(render);

// [getDataFromServer,preprocessBeforeRendering,render].reduce((p,fn)=>p.then(fn),Promise.resolve());

// const applyAsync = (p,fn) => p.then(fn);
// const composeAsync = (...funcs) => funcs.reduce(applyAsync,Promise.resolve());
// composeAsync(getDataFromServer,preprocessBeforeRendering,render);

Promise.resolve(),手动创建一个已经resolve的Promise对象。

async…await

//index.js
function getDataFromServer(){
    return fetch("/data").then(function(response){
        return response.json();
    }).then(function(user){
        return user;
    })
}
function preprocessBeforeRendering(user){
    return `${user.name}他现在在${user.address}`;
}
function render(htmlString){
    document.body.innerHTML = htmlString;
}
async function init(){
    const user = await getDataFromServer();
    const htmlString = preprocessBeforeRendering(user);
    render(htmlString);
}
init();
  • async function
    返回一个Promise对象
  • await
    该关键词只在async function内有效

async...await允许我们以类似同步方式书写异步代码。
Promise对象与async函数

相关标签: javascript