async和await的返回值——NodeJS,getreturnvaluefromasy。。
在ES6和ES5中promise的执⾏也有不同点(上述提到,ES6中promise属microtask;在ES5中,暂未接触到有api直接操作microtask的,所以.then的异步是⽤setTimeout代替,属macrotask,导致输出有差异);关于promise也可参考上⽂
==  ============》
以前没有直接操作 microtask的api
这段代码,实现的功能就是操作micro tasks and macro tasks
let pushToMicroTask = f => solve().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 :
-------------------------------------------------------------------------------------------
await 是⼀个操作符, await 后⾯接 expression
var a = await 3,
async 加在函数前⾯,⾃动返回的是⼀个 Promise
在函数⾥⾯,可以使⽤ await 调⽤前⾯的async定义的函数
全局环境,直接await 就可以, “局部”函数⾥⾯,函数前⾯要加 async关键字
局部函数
参考:
I have an async await function that uses mongoose:
const createModelB = async (id) => {
try {
let user = await User.findOne({id: id});
if (user) {
await和async使用方法let modelB = new ModelB({ user_id: user.id });
modelB = await scrum.save();
return modelB;
}
return null;
} catch (err) {
<(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的值。
function fetchUser() {
return checkAuth()
.then(auth => { return getUser(auth) })
.then(user => { return user });
}
fetchUser().then((user) => console.log(user.name));
  ---------------------------------------
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));

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。