Are nested promises normal in node.js?

前端 未结 7 1949
说谎
说谎 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:39

    I removed the unnecessary nesting. Ill use syntax from 'bluebird'(my preferred Promise library) http://bluebirdjs.com/docs/api-reference.html

    var employeePage;
    
    driver.get('https://website.com/login').then(function() {
        return loginPage.login('company.admin', 'password');
    }).then(function() {
        employeePage = new EmployeePage(driver.getDriver());    
        return employeePage.clickAddEmployee();
    }).then(function () {
        var deferred = Promise.pending();
        setTimeout(deferred.resolve,750);
        return deferred.promise;
    }).then(function() {
        var addEmployeeForm = new AddEmployeeForm(driver.getDriver());
        return Promise.all([addEmployeeForm.insertUserName(employee.username),
                            addEmployeeForm.insertFirstName(employee.firstName),
                            addEmployeeForm.insertLastName(employee.lastName)]);
    }).then(function() {
        return addEmployeeForm.clickCreateEmployee();
    }).then(function() {
        return employeePage.searchEmployee(employee);
    }).catch(console.log);
    

    I modified your code to include examples for all you questions.

    1. There is no need to use the async library when working with promises. Promises are a very powerful by themselves and I think its an anti-pattern to mix promises and libraries like async.

    2. Normally you should avoid using the var deferred = Promise.pending() style...unless

    'when wrapping a callback API that doesn't follow the standard convention. Like setTimeout:'

    https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns

    For the setTimeout example..create a 'deferred' promise...resolve the promise inside setTimeout and then return the promise outside setTimeout. This might seem a little unintuitive. Look at this example, I answered another question. Q.js promise with node. Missing error handler on `socket`. TypeError: Cannot call method 'then' of undefined

    Normally, you can get away with using Promise.promisify(someFunction) to convert a callback type function into a Promise returning function.

    1. Promise.all Lets say your are making multiple calls to an service that return asynchronously. If they don't depend on each other, you can make the calls simultaneously.

    Just pass the function calls as an array. Promise.all([promiseReturningCall1, promiseReturningCall2, promiseReturningCall3]);

    1. Finally add a catch block to the very end..to make sure you catch any error. This will catch any exception anywhere in the chain.

提交回复
热议问题