Are nested promises normal in node.js?

前端 未结 7 1929
说谎
说谎 2020-12-12 13:12

The problem I have been struggling with for two weeks now while learning node.js is how to do synchronous programming using node. I found that no matter how I try to do thin

相关标签:
7条回答
  • 2020-12-12 13:45

    Use async library and use async.series instead of nested chainings which looks really ugly and hard to debug/understand.

    async.series([
        methodOne,
        methodTwo
    ], function (err, results) {
        // Here, results is the value from each function
        console.log(results);
    });
    

    The Promise.all(iterable) method returns a promise that resolves when all of the promises in the iterable argument have resolved, or rejects with the reason of the first passed promise that rejects.

    var p1 = Promise.resolve(3);
    var p2 = 1337;
    var p3 = new Promise(function(resolve, reject) {
      setTimeout(resolve, 100, "foo");
    }); 
    
    Promise.all([p1, p2, p3]).then(function(values) { 
      console.log(values); // [3, 1337, "foo"] 
    });
    

    The Promise.resolve(value) method returns a Promise object that is resolved with the given value. If the value is a thenable (i.e. has a then method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value.

    var p = Promise.resolve([1,2,3]);
    p.then(function(v) {
      console.log(v[0]); // 1
    });
    

    https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

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