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

前端 未结 5 1478
被撕碎了的回忆
被撕碎了的回忆 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.

    0 讨论(0)
  • 2020-12-15 09:17

    .then() is for Promises. You also want to pass the function, not its return type as the .then() parameter. To make your example work, try:

    function one(){
      return Promise.resolve(console.log("one"));
    }
    function two(){
      return Promise.resolve(console.log("two"));
    }
    function three(){
      return Promise.resolve(console.log("three"));
    }
    
    one()
      .then(two)
      .then(three)
      .catch(error => { 
        console.error('uhoh');
      });
    

    Also, while this may work for your example. You won't normally use Promise.resolve(). You'll find it more typical to see the constructor used:

    function func(a, b) {
      return new Promise((resolve, reject) => {
        if (!a || !b) return reject('missing required arguments');
        return resolve(a + b);
      }
    }
    

    Calling reject on an error condition, and resolve on success. Rejections are routed to the first .catch(). I encourage you to read up on Promises in the link above.

    0 讨论(0)
  • 2020-12-15 09:23

    Then is usually used in the context of Promises. You could start reading more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then

    0 讨论(0)
  • 2020-12-15 09:31

    the .then() function is used for the PROMISE (so for async function ) when you need to KNOW WHEN IT'S FINISHED (and it is finished ok .. or KO ) ..so you have

    MYASYNCFUNCTION().then(function(response({
    
     //do what you want when it's finish and everything ok .. with the result
    
    }).catch(function(error){
     // it's finshed but with error
    })
    

    IN your example .. you don't have .then() function cause they're simple function .. but if you want to have it (i don't know why . they've not async stuff inside .. but you can)

    so

    // install it via npm install promise

    var Promise = require('promise');
    
    function one(){
    var promise = new Promise(function (resolve, reject) {
      resolve('one');
      });
    });
    
    }
    

    and then

    one().then(function(resp){ console.log(resp) })
    

    Hope it helps you!!

    0 讨论(0)
  • 2020-12-15 09:34

    .then only works if the function returns a Promise. Promises are used for asynchronous tasks, so you can wait on something before doing something else.

    function one(){
      return new Promise(resolve => {
        setTimeout(() => {
          console.log('one')
          resolve();
         }, 1000);
      });
    }
    
    function two(){
      return new Promise(resolve => {
        setTimeout(() => {
          console.log('two')
          resolve();
         }, 1000);
      });
    }
    
    function three(){
      return new Promise(resolve => {
        setTimeout(() => {
          console.log('three')
          resolve();
         }, 1000);
      });
    }
    
    one().then(two).then(three);

    You can use the resolve (and second argument reject) to return a result to the next .then or .catch:

    function one(){
      return new Promise(resolve => {
        setTimeout(() => {
          resolve('one');
         }, 1000);
      });
    }
    
    function two(){
      return new Promise(resolve => {
        setTimeout(() => {
          resolve('two');
         }, 1000);
      });
    }
    
    function three(){
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          reject(new Error('three'));
         }, 1000);
      });
    }
    
    one()
      .then((msg) => {
        console.log('first msg:', msg);
        return two();
      })
      .then((msg) => {
        console.log('second msg:', msg);
        return three();
      })
      .then((msg) => {
        // This one is never called because three() rejects with an error and is caught below.
        console.log('third msg:', msg);
      })
      .catch((error) => {
        console.error('Something bad happened:', error.toString());
      });

    0 讨论(0)
提交回复
热议问题