promise的问题
发布于 9 年前 作者 bismarch 3290 次浏览 最后一次编辑是 8 年前 来自 问答

请问像官方的http请求代码怎么能用Q实现返回promise呢,实习生没人带,求大神指导

var options = {
  hostname: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': postData.length
  }
};

var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

// write data to request body
req.write(postData);
req.end();
4 回复

@i5ting 看了,主要是http.request会在回调前返回一个req,回调中返回res我就不知道怎么处理了

@bismarch q里面有一个design目录,是1到7版本的实现,是学习promise/a+的非常好的例子

我是用的原生promise的 根据bluebird写的 但是q应该差不多 自豪地采用 CNodeJS ionic

回到顶部