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
相关推荐
SomeOtherTime2 小时前
node.js基础(AI回答)
node.js
雨季mo浅忆21 小时前
记录Node.js安全漏洞及其内置Brotli解码器问题
node.js·安全性测试
tommyjiatong21 小时前
资安底座连环雷:从 PHP2Shell 到 Node2Shell
node.js·php
SEO_juper1 天前
Bash 交叉验证 robots.txt 和 sitemap:两个文件自相矛盾,页面永远收录不了
开发语言·python·node.js·json·bash
SEO_juper1 天前
Go 站点地图生成器:从首页爬全站,一键生成 sitemap.xml
xml·开发语言·人工智能·golang·node.js·seo·外贸独立站
Moshow郑锴2 天前
Ansible 批量部署 Node.js 服务:ZIP 直解与共享目录分发两种方案对比
node.js·ansible
少年的范儿2 天前
Windows 安装 Node.js 教程:nvm 版本管理 + pnpm 安装配置
windows·npm·node.js
peach2 天前
同样是装依赖,为什么 npm 长成 node_modules,Maven 长成 .m2
npm·node.js·maven
FungLeo2 天前
成为全栈·Go 后端篇·重写之前先锁基线:契约、Node 版本与行为清单
golang·node.js·go·openapi·契约测试·成为全栈
FungLeo3 天前
成为全栈·Go 后端篇·契约一致性与差分测试:两套实现如何互相校验
golang·node.js·go·合约测试·差分测试·成为全栈·api兼容