Removing nested promises

后端 未结 2 1084
后悔当初
后悔当初 2020-11-22 00:13

I\'m new to promises and writing network code using requests and promises in NodeJS.

I would like to remove these nested promises and chain them instead, but I\'m no

2条回答
  •  花落未央
    2020-11-22 00:51

    From every then callback, you will need to return the new promise:

    exports.viewFile = function(req, res) {
        var fileId = req.params.id;
        boxContentRequest('files/' + fileId + '/content', req.user.box.accessToken)
          .then(function(response) {
              return boxViewerRequest('documents', {url: response.request.href}, 'POST');
          })
          .then(function(response) {
              return boxViewerRequest('sessions', {document_id: response.body.id}, 'POST');
          })
          .then(function(response) {
              console.log(response);
          });
    };
    

    The promise that is returned by the .then() call will then resolve with the value from the "inner" promise, so that you easily can chain them.

    Generic pattern:

    somePromise.then(function(r1) {
        return nextPromise.then(function(r2) {
            return anyValue;
        });
    }) // resolves with anyValue
    
         ||
        \||/
         \/
    
    somePromise.then(function(r1) {
        return nextPromise;
    }).then(function(r2) {
        return anyValue;
    }) // resolves with anyValue as well
    

提交回复
热议问题