How to use .then() in node.js?

前端 未结 5 1477
被撕碎了的回忆
被撕碎了的回忆 2020-12-15 09:02

I\'m a complete beginner in node.js. I\'ve just read we can use .then() function for executing several functions in particular order. I was going t

5条回答
  •  囚心锁ツ
    2020-12-15 09:11

    .then is a method that exists on Promises and is a mechanism for code synchronization. Your code is not asynchronous, so you wouldn't need to use promises. You can just call

    one();
    two();
    three();
    

    If your code does something asynchronous, then you can use promises and .then. Asynchronous operations are things like reading/writing files, http requests, timers, and many more.

    Just as an example, we can use the built in Promise to create our own asynchronous operations:

    I don't recommend you do this normally. We're just using it as an example. In most cases you can call functions that already return promises for you.

    function one() {
      return new Promise(resolve => {
        console.log("one");
        resolve();
      });
    }
    
    function two() {
      return new Promise(resolve => {
        console.log("two");
        resolve();
      });
    }
    
    function three(){
       console.log("three")
    }
    
    one().then(() => two()).then(() => three());
    

    Also note that when you use .then, you need to pass a callback. two() calls the two function immediately, so it's not the same as () => two().


    Next, you can often use async/await instead of .then which I think makes your code easier to reason about in most cases.

    async function run() {
      await one();
      await two();
      three();
    }
    run();
    

    This is the same as the second example rewritten to use await instead of .then. You can think of everything after await as being inside of a .then chained to the expression after await.


    Finally, you should handle errors by either chaining .catch to the promises or using the normal try/catch inside of async functions.

提交回复
热议问题