2023-10-19 node.js-将异步处理修改为同步-使用Promise和async-记录

摘要:

2023-10-19 node.js-将异步处理修改为同步-使用Promise和async-记录

使用promise和async将异步修改为同步:

javascript 复制代码
const fs = require('fs');

f1 = function() {
    return new Promise(resolve => {
        fs.readFile('f1.txt', 'utf8', (err, data) => {
            if (err) reject(err);
            else resolve(data);
        });
    });
}

async function asyncCall() {
    console.log('calling');
    const result = await f1();
    console.log(result);
    return result;
}

asyncCall();

思路分析:

  1. 将异步操作使用 Promise 处理,返回值用 resolve(data) 返回
  2. 调用 包裹 Promise 的函数, 使用 await
  3. 注意asyncCall函数,在这个函数, 使用async处理,在里面调用异步函数f1
相关推荐
coderCN14 小时前
Nodejs 响应头和请求头
后端·node.js
__zRainy__16 小时前
Node系列 · ORM:log4js 日志记录
node.js·log4j
秋秋小事1 天前
node 导入与导出
node.js
秋秋小事1 天前
node event模块
node.js
晴天161 天前
Node.js 中 `npm install` 命令分析-Day30
前端·npm·node.js
晴天161 天前
VS Code `launch.json` 指南(Node.js版)-Day30
node.js·json
空の鱼2 天前
Mac 上 Node 版本管理(brew + nvm 共存方案)
macos·node.js
请你吃div2 天前
Node 后端项目 Docker 自动部署教程(GitHub + 宝塔 + Self-hosted Runner)
后端·docker·node.js
泠曦れいひ2 天前
在当前项目中安装Vite
前端框架·npm·node.js
Joseph 乔2 天前
【NVM】node 和 nvm 卸载(安装 node & nvm & npm & cnpm & yarn 及配置)
npm·node.js