我不熟悉承諾和使用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, 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);
});
});
}
任何瞭解,將不勝感激。
您可能需要[請求 - 承諾](https://github.com/tyabonil/request-promise)。有了這個lib,你可以保存一些代碼來將請求包裝到承諾中。 –