小编典典

JavaScript删除嵌套的承诺

javascript

我是诺言和使用NodeJS中的请求和诺言编写网络代码的新手。

我想删除这些嵌套的Promise,而是将它们链接起来,但是我不确定我将如何处理它/这是否是正确的方法。

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

这是请求代码:

var baseContentURL = 'https://api.box.com/2.0/';
var baseViewerURL = 'https://view-api.box.com/1/';

function boxContentRequest(url, accessToken) {
    return new Promise(function (resolve, reject) {
            var options = {
                url: baseContentURL + url,
                headers: {
                    Authorization: 'Bearer ' + accessToken,
                }
            };
      request(options, function (err, res) {
        if (err) {
          return reject(err);
        } else if (res.statusCode !== 200) {
          err = new Error("Unexpected status code: " + res.statusCode);
          err.res = res;
          return reject(err);
        }
        resolve(res);
      });
    });
}

function boxViewerRequest(url, body, method) {
    return new Promise(function (resolve, reject) {
            var options = {
                method: method,
                url: baseViewerURL + url,
                headers: {
                    Authorization: 'Token ' + config.box.viewerApiKey
                },
                json: body
            };
      request(options, function (err, res, body) {
        if (err) {
          return reject(err);
        } else if (res.statusCode !== 200 && res.statusCode !== 201 && res.statusCode !== 202) {
          err = new Error("Unexpected status code: " + res.statusCode);
          err.res = res;
          return reject(err);
        }
        resolve(res, body);
      });
    });
}

任何见识将不胜感激。


阅读 356

收藏
2020-04-25

共1个答案

小编典典

在每个then回调中,您都需要 返回 新的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);
      });
};

.then()调用返回的承诺然后将使用“内部”承诺中的值进行解析,以便您可以轻松地链接它们。

通用模式:

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
2020-04-25