Promise对象与async函数

环境搭建
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 new Promise((resolve,reject) => {
//         const XHR = new XMLHttpRequest();
//         XHR.open("get","/data/1");
//         XHR.onreadystatechange = function(){
//             if(XHR.status===200 && XHR.readyState===4){
//                 resolve(JSON.parse(XHR.response));
//             }else{
//                 reject(XHR.statusText);
//             }
//         }
//         XHR.send();
//     })
// }

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对象。

异步之加载图像
function loadedImgAsync(url,elm){
    return new Promise((resolve,reject) => {
        var img = new Image();
        img.onload = function(){
            resolve(`loaded image at ${url}`)
        }
        img.onerror = function(){
            reject(new Error(`could not loaded image at ${url}`));
        }
        img.src = url;
        elm.appendChild(img);
    })
}

// loadedImgAsync("./imgs/d.png",document.body)
// .then(
//     tip => console.log(tip),
//     err => console.log(err)
// );

loadedImgAsync("./imgs/d.png",document.body)
.then(tip => console.log(tip))
.catch(tip => console.log(tip));
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允许我们以类似同步方式书写异步代码。
在这里插入图片描述

异步之定时器
const timeout = ms => new Promise(resolve => setTimeout(resolve,ms));
const asyncPrint = async (value,ms) => {
    await timeout(ms);
    console.log(value);
}
asyncPrint("hello world",1000*2);

刷新页面2秒后,控制台打印出"hello world"。

异步之读取文件
const fs = require("fs");
const readFile = (url) => {
    return new Promise((resolve,reject) => {
        fs.readFile(url,"utf8",(err,data) => {
            if(err) reject(err);
            resolve(data);
        })
    })
}
const asyncReadFile = async (url) => {
    const fileContent = await readFile(url);
    console.log(fileContent);
}

asyncReadFile("./index.html");
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值