• express promise async await promisify


    Promise 概述

    Promise 是 JavaScript 中异步编程解决方案,可以解决回调函数方案中的回调地狱问题可以将 Promise 理解为容器,用于包裹异步 API的容器,当容器中的异步 API执行完成后,Promise 允许我们在容器的外面获取异步API的执行结果,从而避免回调函数嵌套。Promise 翻译为承若,表示它承若帮我们做一些事情,既然它承若了它就要去做,做就会有一个过程、就会有一个结果,结果要么是成功要么是失败。
    所以在 Promise 中有三种状态,分别为等待(pending),成功(fulfilled),失败(rejected)。默认状态为等待,等待可以变为成功,等待可以变为失败状态一旦更改不可改变,成功不能变回等待,失败不能变回等待,成功不能变成失败,失败不能变成成功。

    在这里插入图片描述

    Promise示例代码

    示例1

    let myPro = new Promise((resolve, reject)=>{
        setTimeout(()=>{
            resolve(5)
        },1000)
    }).then(() => {
        console.log(123)
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    输出

    123
    
    • 1

    示例2

    let myPro = new Promise((resolve, reject)=>{
        const currentTime = new Date();
        const formattedTime = `${currentTime.getHours()}:${currentTime.getMinutes()}:${currentTime.getSeconds()}:${currentTime.getMilliseconds()}`;
        console.log(formattedTime);
        for (let i = 0; i < 1000000000; i++) {
    
        }
        resolve()
    }).then(() => {
    
    })
    const currentTime = new Date();
    const formattedTime = `${currentTime.getHours()}:${currentTime.getMinutes()}:${currentTime.getSeconds()}:${currentTime.getMilliseconds()}`;
    console.log(formattedTime);
    console.log(123)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    输出:

    20:18:50:45
    20:18:50:486
    123
    
    • 1
    • 2
    • 3

    示例3

    let p1 = new Promise((resolve, reject) => setTimeout(reject, 300, "失败"))
    let p2 = new Promise(resolve => setTimeout(resolve, 100, 2))
    let p3 = 3
    const currentTime = new Date();
    const formattedTime = `${currentTime.getHours()}:${currentTime.getMinutes()}:${currentTime.getSeconds()}:${currentTime.getMilliseconds()}`;
    console.log(formattedTime);
    Promise.all([p1, p2, p3]).then(value => {
        const currentTime = new Date();
        const formattedTime = `${currentTime.getHours()}:${currentTime.getMinutes()}:${currentTime.getSeconds()}:${currentTime.getMilliseconds()}`;
        console.log(formattedTime);
        console.log(value)
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    输出

    20:43:12:671
    (node:25908) UnhandledPromiseRejectionWarning: 失败                    
    (Use `node --trace-warnings ...` to show where the warning was created)
    (node:25908) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch blo
    ck, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejec
    tions=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
    (node:25908) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the No
    de.js process with a non-zero exit code.
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    Promise.all 并发操作

    示例1

    Promise.all([
        readFile('D:\\work\\jjBest\\0.txt'),
        readFile('D:\\work\\jjBest\\1.txt'),
        readFile('D:\\work\\jjBest\\2.txt')
    ]).then(function (res) {
        console.log(res)
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    示例2

    let p1 = new Promise(resolve => setTimeout(resolve, 300, 1))
    let p2 = new Promise(resolve => setTimeout(resolve, 100, 2))
    let p3 = 3
    const currentTime = new Date();
    const formattedTime = `${currentTime.getHours()}:${currentTime.getMinutes()}:${currentTime.getSeconds()}:${currentTime.getMilliseconds()}`;
    console.log(formattedTime);
    Promise.all([p1, p2, p3]).then(value => {
        const currentTime = new Date();
        const formattedTime = `${currentTime.getHours()}:${currentTime.getMinutes()}:${currentTime.getSeconds()}:${currentTime.getMilliseconds()}`;
        console.log(formattedTime);
        console.log(value)
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    输出

    20:39:25:180
    20:39:25:483
    [ 1, 2, 3 ]
    
    • 1
    • 2
    • 3

    Promise.allSettled

    示例1

    let p1 = new Promise((resolve, reject) => setTimeout(reject, 300, "失败"))
    let p2 = new Promise(resolve => setTimeout(resolve, 100, 2))
    let p3 = 3
    const currentTime = new Date();
    const formattedTime = `${currentTime.getHours()}:${currentTime.getMinutes()}:${currentTime.getSeconds()}:${currentTime.getMilliseconds()}`;
    console.log(formattedTime);
    Promise.allSettled([p1, p2, p3]).then(value => {
        const currentTime = new Date();
        const formattedTime = `${currentTime.getHours()}:${currentTime.getMinutes()}:${currentTime.getSeconds()}:${currentTime.getMilliseconds()}`;
        console.log(formattedTime);
        console.log(value)
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    输出

    20:45:57:235
    20:45:57:543
    [                                        
      { status: 'rejected', reason: '失败' },
      { status: 'fulfilled', value: 2 },     
      { status: 'fulfilled', value: 3 }      
    ] 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    async

    加上async就是异步函数了,返回值类型为Promise
    返回值会自动包裹在promise中

    示例1

    async function getTitle(){
        return "标题"
    }
    console.log(getTitle())
    
    • 1
    • 2
    • 3
    • 4
    Promise { '标题' }
    
    • 1

    示例2

    async function getTitle() {
        return "标题"
    }
    
    getTitle().then(value => console.log(value))
    
    • 1
    • 2
    • 3
    • 4
    • 5

    输出

    标题
    
    • 1

    await

    异步函数关键字 await

    await 关键字后面只能放置返回 Promise 对象的 API。
    await 关键字可以暂停函数执行,等待 Promise
    执行完后返回执行结果 await 关键字只能出现在异步函数中。

    示例1

    function readFile(path){
        return new Promise(function (resolve, reject) {
            fs.readFile(path,'utf-8',function (err, data) {
                if (err){
                    reject(err)
                }else {
                    resolve(data)
                }
            })
        })
    }
    
    // 加上async就是异步函数了
    async function run(){
        let x = await readFile('D:\\work\\jjBest\\0.txt');
        console.log(x)
        let y = await readFile('D:\\work\\jjBest\\1.txt');
        console.log(y)
        return [x,y]
    }
    run().then(function (res) {
        console.log(res)
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    示例2

    function testWait() {
        return new Promise((resolve, reject) => {
            setTimeout(function () {
                console.log("testWait");
                resolve();
            }, 1000);
        })
    }
    
    async function testAwaitUse(){
        await testWait()
        console.log("hello")
        return "test"
    }
    console.log(testAwaitUse())
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    输出

    Promise {  }
    testWait
    hello
    
    • 1
    • 2
    • 3

    示例3

    function testWait() {
        return new Promise((resolve, reject) => {
            setTimeout(function () {
                console.log("testWait");
                resolve();
            }, 1000);
        })
    }
    
    async function testAwaitUse(){
        testWait()
        console.log("hello")
        return "test"
    }
    console.log(testAwaitUse())
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    输出

    hello             
    Promise { 'test' }
    testWait
    
    • 1
    • 2
    • 3

    promisify

    使用promisify后,不用声明readFile的promise函数了。

    const promisify = require('util').promisify
    const readFile = promisify(fs.readFile)
    
    // 加上async就是异步函数了
    async function run() {
        let x = await readFile('D:\\work\\jjBest\\0.txt', "utf-8");
        console.log(x)
        let y = await readFile('D:\\work\\jjBest\\3.txt', "utf-8");
        console.log(y)
        return [x, y]
    }
    
    run().then(function (res) {
        console.log(res)
    }).catch(function (err) {
        console.log(err)
    })
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
  • 相关阅读:
    安全可靠的文件传输服务助力完成更高效的医疗保健工作(上)
    同时申请发明专利和实用新型专利的好处
    C# SIMD向量加速运算简单例子
    海康威视-下载的录像视频浏览器播放问题
    Leetcode1608. 特殊数组的特征值
    Windows下,ESP-IDF&ESP-ADF的安装
    【微服务】SpringCloud微服务续约源码解析
    systemverilog function的一点小case
    Oracle导出clob字段到csv
    FFmpeg入门详解之24:短视频技术原理
  • 原文地址:https://blog.csdn.net/qq_42015021/article/details/134042733