我有一些代码:
var bar = foo().then(function success(value) {
// compute something from a value...
}, function failure(reason) {
// handle an error...
});
Run Code Online (Sandbox Code Playgroud)
如何在上下文中将failure函数绑定到this对象bar.我知道我将不得不使用myFunc.bind(this)但我可以替代什么myFunc?
我试图使用Node.js supertest来测试我编写的一些REST API.我需要发送一个等同于以下CURL请求的请求:
curl -X POST -F api_key=KEY -F image=@my_file http://localhost:3000/v1/upload
Run Code Online (Sandbox Code Playgroud)
我尝试了以下,但我得到了Uncaught TypeError: first argument must be a string or Buffer.
request.post('/v1/upload')
.type('form')
.field('api_key', 'abcd')
.attach('image', 'some path')
.end(function(err, res) {
res.body.error.should.equal('Invalid username/api_key.');
done();
});
Run Code Online (Sandbox Code Playgroud)
我也试过发送它:
request.post('/v1/upload')
.type('form')
.field('api_key', 'abcd')
.attach('image', 'some path')
.end(function(err, res) {
res.body.error.should.equal('Invalid username/api_key.');
done();
});
Run Code Online (Sandbox Code Playgroud)
但服务器只能解析文件上传请求而不是api_key.
如果我有一个运行Node.js的Web服务器,那么我能同时提供多个请求吗?从我的初步测试中我可以看到,Node主要是单线程,目前只能处理一个HTTP请求.但是如果一个请求需要很长时间才能完成(例如,上传大数据),那么所有其他请求都必须等待.
这种情况有解决方法吗?我们可以编写代码,以便它可以同时服务多个HTTP请求吗?
为什么以下代码每次都会生成不同的输出(不是因为随机函数),但它为某些值(有时是其他值)提供了未定义的值.问题是什么?
function getRandom(ubound) {
return Math.floor((Math.random()*10) % ubound);
}
function getInterval() {
var interval = [getRandom(10), getRandom(10)];
if(interval[1] >= interval[0])
return interval;
else
getInterval();
}
function generateIntervals() {
for(var i = 0; i < n; i++)
intervals[i] = getInterval();
}
function printIntervals() {
for(var i = 0; i < n; i++)
console.log("Node " + (i + 1) + ": " + intervals[i]);
}
generateIntervals();
printIntervals();
Run Code Online (Sandbox Code Playgroud)
我得到的输出如下:
Node 1: 0,9
Node 2: 0,3
Node 3: undefined
Node 4: 2,2
Run Code Online (Sandbox Code Playgroud)
要么
Node …Run Code Online (Sandbox Code Playgroud)