删除嵌套的承诺
我不熟悉NodeJS中的使用请求和承诺的承诺和编写networking代码。
我想删除这些嵌套的承诺,并链接他们,但我不知道我会怎么做/是否是正确的路要走。
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); }); }); }
任何有识之士将不胜感激。
从每一个callback中,你都需要返回新的承诺:
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