Removing nested promises

后端 未结 2 1080
后悔当初
后悔当初 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条回答
  •  -上瘾入骨i
    2020-11-22 00:52

    Promise.prototype.then is designed to return another promise, so that you can chain them.

    The handler function passed to .then() can return a normal value, like a number or string or object, and this value will get passed on to the next handler of .then().

    One option is to have boxViewerRequestSync be a synchronous function that returns a response object:

    boxContentRequest('files/' + fileId + '/content', req.user.box.accessToken)
        .then(function(response) {
            return boxViewerRequestSync('documents', {url: response.request.href}, 'POST')
        })
        .then(function(response) { // this `response` is returned by `boxViewerRequestSync`
            return boxViewerRequestSync('sessions', {document_id: response.body.id}, 'POST')
        })
        .then(function(response) {
            console.log(response);
        })
    

    But of course your boxViewerRequest is asynchronous and returns a promise instead. In that case, the handler function passed to .then() could also return a completely unrelated Promise. This new promise is executed synchronously, and once it is resolved/rejected, its result is passed on to the next handler.

    boxContentRequest('files/' + fileId + '/content', req.user.box.accessToken)
        .then(function(response) {
            return boxViewerRequest('documents', {url: response.request.href}, 'POST')
        })
        .then(function(response) { // this `response` is the result of resolving the promise returned by `boxViewerRequest`
            return boxViewerRequest('sessions', {document_id: response.body.id}, 'POST')
        })
        .then(function(response) {
            console.log(response);
        })
    

    Keeping track of all the promises is confusing, but the bottom line is this: Promise.prototype.then will always return a Promise object, but the handler function passed to Promise.prototype.then can return anything, even undefined, or even another Promise. Then that value, or the value of the resolved Promise, is passed to the next handler function.

提交回复
热议问题