我是新来的承诺和编写一些网络代码使用请求和承诺在NodeJS.
我想删除这些嵌套的承诺,并链接它们,但我不知道我会如何去做/是否是正确的方法.
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,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); }); }); }
任何见解将不胜感激.
解决方法
从每一个回调,你将需要返回新的承诺:
exports.viewFile = function(req,res) { var fileId = req.params.id; BoxContentRequest('files/' + fileId + '/content',req.user.Box.accessToken) .then(function(response) { return BoxViewerRequest('documents','POST'); }) .then(function(response) { return BoxViewerRequest('sessions','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