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

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/

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

  

猜你喜欢

转载自www.cnblogs.com/oxspirt/p/10196252.html
今日推荐