async和await的返回值——NodeJS, get return value from async await
在ES6和ES5中promise的执行也有不同点(上述提到,ES6中promise属microtask;在ES5中,暂未接触到有api直接操作microtask的,所以.then的异步是用setTimeout代替,属macrotask,导致输出有差异);关于promise也可参考上文 分步理解 Promise 的实现
== ============》
以前没有直接操作 microtask的api
这段代码,实现的功能 就是操作micro tasks and macro tasks
1 2 3 4 5 6 | let pushToMicroTask = f => Promise.resolve().then(f); let pushToMacroTask = f => setTimeout(f); let say = msg => console.log(msg); pushToMacroTask(say.bind( null , 'Macro task runs last' )); pushToMicroTask(say.bind( null , 'Micro task runs first' )); |
Is there is any W3C spec concerning micro/macro tasks?
W3C speaks of task queues:
-------------------------------------------------------------------------------------------
await 是一个操作符, await 后面接 expression
var a = await 3,
async 加在函数前面,自动返回的是一个 Promise
在函数里面,可以使用 await 调用前面的async定义的函数
全局环境,直接await 就可以, “局部”函数 里面,函数前面要加 async关键字
局部函数
参考: https://stackoverflow.com/questions/48375499/nodejs-get-return-value-from-async-await
https://www.academind.com/learn/javascript/callbacks-vs-promises-vs-rxjs-vs-async-awaits/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | I have an async await function that uses mongoose: const createModelB = async (id) => { try { let user = await User.findOne({id: id}); if (user) { let modelB = new ModelB({ user_id: user.id }); modelB = await scrum.save(); return modelB; } return null ; } catch (err) { console.error(err); } return null ; }; Now then I'm calling this function from somewhere else : let modelB = createModelB(123); console.log(modelB); Instead of outputting Models fields, console returns to me this : Promise {<pending>} What did I miss? |
下面这种方式返回promise的值。
1 2 3 4 5 6 | function fetchUser() { return checkAuth() .then(auth => { return getUser(auth) }) .then(user => { return user }); } fetchUser().then((user) => console.log(user.name)); |
---------------------------------------
1 2 3 4 5 6 | async function fetchUser() { const auth = await checkAuth(); // <- async operation const user = await getUser(auth); // <- async operation return user; } fetchUser().then((user) => console.log(user.name)); |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
2017-12-29 TMUX会话的使用