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 

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

  

 

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/

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

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM