在ES6和ES5中promise的执行也有不同点(上述提到,ES6中promise属microtask;在ES5中,暂未接触到有api直接操作microtask的,所以.then的异步是用setTimeout代替,属macrotask,导致输出有差异);关于promise也可参考上文 分步理解 Promise 的实现

==  ============》

以前没有直接操作 microtask的api 

https://stackoverflow.com/questions/41075724/javascript-api-to-explicitly-add-micro-tasks-or-macro-tasks

这段代码,实现的功能 就是操作micro tasks and macro tasks

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'));

  async和await的返回值——NodeJS, get return value from async await

 

Is there is any W3C spec concerning micro/macro tasks?

W3C speaks of task queues:

 

 

-------------------------------------------------------------------------------------------

 

await 是一个操作符, await 后面接 expression

var a = await 3,

 async和await的返回值——NodeJS, get return value from async await

async 加在函数前面,自动返回的是一个 Promise

async和await的返回值——NodeJS, get return value from async await

在函数里面,可以使用 await 调用前面的async定义的函数

全局环境,直接await 就可以, “局部”函数 里面,函数前面要加 async关键字

async和await的返回值——NodeJS, get return value from async await

 

 局部函数

async和await的返回值——NodeJS, get return value from async await

 

 

 

参考: 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/

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的值。

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));

  

相关文章: