我已经开发了几年的JavaScript,我根本不理解有关承诺的大惊小怪.
似乎我所做的只是改变:
api(function(result){
api2(function(result2){
api3(function(result3){
// do work
});
});
});
Run Code Online (Sandbox Code Playgroud)
无论如何,我可以使用像async这样的库,例如:
api().then(function(result){
api2().then(function(result2){
api3().then(function(result3){
// do work
});
});
});
Run Code Online (Sandbox Code Playgroud)
哪个代码更多,可读性更低.我没有在这里获得任何东西,它也不会突然神奇地"平坦".更不用说必须将事物转换为承诺.
那么,这里的承诺有什么大惊小怪?
我是承诺并使用NodeJS中的请求和承诺编写网络代码的新手.
我想删除这些嵌套的promises并将它们链接起来,但我不确定我是怎么做的/它是否是正确的方法.
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);
});
});
});
};
Run Code Online (Sandbox Code Playgroud)
这是请求代码:
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) { …Run Code Online (Sandbox Code Playgroud) 我正在编写一个JavaScript函数,它发出HTTP请求并返回结果的承诺(但这个问题同样适用于基于回调的实现).
如果我立即知道为函数提供的参数是无效的,那么函数应该是throw同步的,还是应该返回一个被拒绝的promise(或者,如果你愿意的话,调用一个Error实例的回调)?
异步函数应始终以异步方式运行,特别是对于错误条件,这有多重要?是否确定throw,如果你知道程序是不是一个合适的状态的异步操作继续进行?
例如:
function getUserById(userId, cb) {
if (userId !== parseInt(userId)) {
throw new Error('userId is not valid')
}
// make async call
}
// OR...
function getUserById(userId, cb) {
if (userId !== parseInt(userId)) {
return cb(new Error('userId is not valid'))
}
// make async call
}
Run Code Online (Sandbox Code Playgroud) javascript ×3
promise ×3
api-design ×1
asynchronous ×1
bluebird ×1
callback ×1
node.js ×1
q ×1
request ×1