不能用asynchronous做http请求并等待

试图使用asyncawait在nodejs中执行http请求,但得到错误。 有任何想法吗? 谢谢

 got response: undefined /home/tom/learn/node/node_modules/node-rest-client/lib/node-rest-client.js:539 callback(parsedData,res); ^ TypeError: callback is not a function at /home/tom/learn/node/node_modules/node-rest-client/lib/node-rest-client.js:539:13 at Object.parse (/home/tom/learn/node/node_modules/node-rest-client/lib/nrc-parser-manager.js:151:3) at ConnectManager.handleResponse (/home/tom/learn/node/node_modules/node-rest-client/lib/node-rest-client.js:538:32) at ConnectManager.handleEnd (/home/tom/learn/node/node_modules/node-rest-client/lib/node-rest-client.js:531:18) at IncomingMessage.<anonymous> (/home/tom/learn/node/node_modules/node-rest-client/lib/node-rest-client.js:678:34) at emitNone (events.js:110:20) at IncomingMessage.emit (events.js:207:7) at endReadableNT (_stream_readable.js:1059:12) at _combinedTickCallback (internal/process/next_tick.js:138:11) at process._tickCallback (internal/process/next_tick.js:180:9) 

这是脚本的源代码

 var Client = require('node-rest-client').Client; var client = new Client(); async function test1() { response = await client.get("http://localhost/tmp.txt"); console.log("got response: "); console.log(response.headers); }; test1(); 

在Ubuntu 14.04上,nodejs的版本是v8.4.0。

async/await不只是魔术般的function,期望callback。 如果client.get()期望callback作为参数,那么如果要使用它,则必须传递一个callback。 async/await与返回承诺的asynchronous操作一起工作,并按照这些承诺进行操作。 他们不会奇迹般地让你跳过callback函数来devisecallback。 我会build议更多的阅读关于如何实际使用asyncawait

通常, async/await的path是首先devise所有的async操作,以使用promise和.then()处理程序。 然后,在这一切工作之后,你可以声明一个函数作为你想要使用的asynchronous,然后在那些asynchronous声明的函数中,你可以调用返回promise的函数,而不是使用.then()处理程序。 这里没有魔法捷径。 从承诺devise开始。

这是一个简单的承诺的例子:

 // asynchronous function that returns a promise that resolves to // the eventual async value function delay(t, val) { return new Promise(resolve => { setTimeout(() => { resolve(val); }, t); }); } function run() { return delay(100, "hello").then(data => { console.log(data); return delay(200, "goodbye").then(data => { console.log(data); }); }).then(() => { console.log("all done"); }); } run(); 

而且,这里也适用于使用async/await

 // function returning a promise declared to be async function delay(t, val) { return new Promise(resolve => { setTimeout(() => { resolve(val); }, t); }); } async function run() { console.log(await delay(100, "hello")); console.log(await delay(200, "goodbye")); console.log("all done"); } run(); 

这两个例子都产生相同的输出和相同的输出时序,所以希望你能看到从promise到async / await的映射。

等待需要它的论据来返回一个承诺。 你得到这个错误的原因是client.get(“ http://localhost/tmp.txt ”); 没有兑现承诺。

所以,有两种方法可以解决这个问题。

  1. 明确地返回一个承诺
  2. 使用其他返回promise的库。 例如: https : //www.npmjs.com/package/node-rest-client-promise