在我的场景中,当我提出请求时,我会返回一个承诺.
最后我解决/拒绝延期的obj.
如果尚未解决/拒绝,我想重复使用该承诺.
任何信息都会有用.
所以我在Node.js中创建了这个简单的测试服务器.
每当我做直接响应时,我得到2200个请求/秒(快!).当我只包裹一个简单的Q延迟它时,它下降到580个请求/秒(慢4倍!).任何人都能解释这个巨大的差异吗?
// Requires
var server = require('http');
var q = require('q');
// Start server
var http = require('http');
http.createServer(function(request, response) {
// Comment out either of two below sections
// Without deferred
// 2200 reqs/second
response.writeHead(200, {"Content-Type": "text/html"});
response.write("test");
response.end();
// Q deferred
// 580 reqs/second
var deferred = q.defer();
deferred.promise.then(function() {
response.writeHead(200, {"Content-Type": "text/html"});
response.write("test");
response.end();
});
deferred.resolve();
}).listen(1234);
Run Code Online (Sandbox Code Playgroud) 什么方面的承诺库的不规范不覆盖?实施之间有什么不同?
请举例说明实际差异(例如Bluebird和Q之间).
使用Nodejs Q promise库的.finally()和.done()语句有什么区别.
例如,这两者之间有什么区别?
Q(...)
.then(...)
.finally(); //or fin()
Q(..)
.then()
.done();
Run Code Online (Sandbox Code Playgroud) 我正在为我的系统编写一个API,它将XHR发送到服务器并返回一个应该由调用者处理的promise - 到目前为止一直很好.
对于每个API调用,我必须使用.then和.catch调用,但通常(如75%的时间).catch引用相同的功能,只使用打印console.error.
我的问题是 - 有没有办法为我创建的每个promise附加一个默认的catch语句?(让我们说打印到控制台),对于我希望进一步处理拒绝的每个承诺,我会添加另一个.catch调用(甚至覆盖它)?
每个调用都有自己的.catch的简化示例:http://jsbin.com/waqufapide/edit?js,console
试图实现所需行为的非工作版本:http://jsbin.com/nogidugiso/2/edit?js,console
在第二个示例中,deferred.promise我返回一个附加catch()处理程序的promise ,而不仅仅是返回:
return deferred.promise.catch(function (error) {
console.error(error);
});
Run Code Online (Sandbox Code Playgroud)
这两个then渔获物和then函数调用在这种情况下.
我确实知道Q暴露了getUnhandledReasons()函数和onerror事件,但我真的不想.done()用于每个promise,也不构建某种定时器/间隔来处理未处理的拒绝列表.
其他库,如bluebird暴露onPossiblyUnhandledRejection事件,我不得不承认这是一个更好的解决方案,但仍然不是我正在寻找的.
我有数组(不管是文件队列):
[{deferred: fileDef, data: file}, {...}, ...]
Run Code Online (Sandbox Code Playgroud)
每个fileDef和file发送到上传函数,返回fileDef.promise并在上传后调用fileDef.resolve或fileDef.reject.
我想按顺序上传文件:加载上一个文件后的下一个文件上传.
现在我用
var queue = [];
var uploading = false;
//file input callback call each time the user selects files
function addAndUpload (file) {
queue.push({deferred: $q.defer(), data: file});
if (!uploading) recurceQueue();
function recurceQueue () {
if (queue.length) {
uploading = true;
var fileObj = queue.shift();
upload(fileObj.deferred, fileObj.data);
fileObj.deferred.promise.finally(function () {
uploading = false;
recurceQueue();
})
}
}
}
Run Code Online (Sandbox Code Playgroud)
但它似乎很糟糕.怎么写得更好?
目前我在显示从我的Web服务Node.js服务器(localhost:3000)发送到Node.js服务器上运行的模拟客户端(localhost:3001)的"响应块"时出现问题.
逻辑如下:
1.在"城市"的客户端创建一个数组,并将它们(从AngularJS控制器)发布到位于以下位置的Web服务:localhost:3000/getMatrix
$http({
method: 'POST',
url: 'http://localhost:3000/getMatrix',
data: cityArray
}).
success(function (data,status,headers,config){
// binding of $scope variables
// calling a local MongoDB to store the each data item received
for(var key in data){
$http.post('/saveRoutes', data[key])
.success(function (data, status){
// Data stored
})
.error(function (data, status){
// error prints in console
});
}
}).
error(function (data,status,headers,config){
alert("Something went wrong!!");
});
Run Code Online (Sandbox Code Playgroud)
2.然后,Web服务运行其过程以创建"城市"矩阵(例如,如果它通过了5个城市,它将返回5by5 [25项]的JSON矩阵).但问题是,由于Node的> response.write(数据),它以"块"传回数据.
旁注 - Node.js自动设置标题中的'Transfer-Encoding':'chunked'
* Other code before (routing/variable creation/etc.) *
res.set({
'Content-Type':'application/json; …Run Code Online (Sandbox Code Playgroud) 我有两个功能,都返回承诺:
var getToken = function() {
var tokenDeferred = $q.defer();
socket.on('token', function(token) {
tokenDeferred.resolve(token);
});
//return promise
return tokenDeferred.promise;
}
var getUserId = function() {
var userIdDeferred = $q.defer();
userIdDeferred.resolve('someid');
return userIdDeferred.promise;
}
Run Code Online (Sandbox Code Playgroud)
现在我有一个主题列表,一旦这两个承诺得到解决,我想立即更新
var topics = {
firstTopic: 'myApp.firstTopic.',
secondTopic: 'myApp.secondTopic.',
thirdTopic: 'myApp.thirdTopic.',
fourthTopic: 'myApp.fourthTopic.',
};
Run Code Online (Sandbox Code Playgroud)
已解决的主题应如下所示 myApp.firstTopic.someid.sometoken
var resolveTopics = function() {
$q.all([getToken(), getUserId()])
.then(function(){
//How can I resolve these topics in here?
});
}
Run Code Online (Sandbox Code Playgroud) 我想使用这样的Promise来调用Google Maps Geocoding API:
function makeGeoCodingRequest(address,bounds)
{
/*
Input parameters:
address:a string
bounds: an object of class google.maps.LatLngBounds(southWest,northEast)
This will return a set of locations from the google geocoding library for the given query
*/
var url="https://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&key=AIzaSyD9GBloPC20X-1kWRo7sm_0z5xvCiaSd3c";
var promise,response;
var messages={
"ZERO_RESULTS":"No results were found",
"OVER_QUERY_LIMIT":"We are over the query limit.Wait awhile before making a request",
"REQUEST_DENIED":"Request was denied,probably using a bad or expired API Key",
"INVALID_REQUEST":"Request was sent without the required address,component or component",
"UNKNOWN_ERROR": …Run Code Online (Sandbox Code Playgroud) 我有一个函数需要传递给它的三个先前的承诺的结果.一个是线性相关的,另外两个可以同时运行.我想使用q.all来解决三个promise,然后使用.spread将结果传递给第四个.但是我的代码不起作用.任何帮助,将不胜感激.
var p1 = doWork(data);
var p2 = p1.then(doMoreWork);
var p3 = doConcurrentWork(data);
return q.all([p1,p2,p3]).spread(funcWith3params)
.fail(function(err) {
console.log(err):
}
Run Code Online (Sandbox Code Playgroud)
我可以在node-inspector中跟踪代码,看看是否正在调用前3个promise.但是,.spread调用的函数没有被调用.任何线索为什么?另外.fail也没被击中.
q ×10
javascript ×7
promise ×7
node.js ×4
angularjs ×3
bluebird ×2
deferred ×2
ajax ×1
asynchronous ×1
jquery ×1
rsvp-promise ×1