不能用 async 和 await 做 http 请求

pac*_*tie 3 asynchronous node.js

尝试在 nodejs 中使用asyncawait执行 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)
Run Code Online (Sandbox Code Playgroud)

这是脚本的源代码

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();
Run Code Online (Sandbox Code Playgroud)

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

jfr*_*d00 5

async/await不要只是神奇地使用期望回调的函数。如果 client.get() 期望回调作为参数,则必须传递回调才能使用它。async/await使用返回承诺的异步操作,并在这些承诺上进行操作。它们不会神奇地让您跳过将回调传递给为回调设计的函数。我建议阅读更多关于如何实际使用async和的阅读材料await

通常,路径async/await是首先设计所有async操作以使用承诺和.then()处理程序。然后,在这一切都工作之后,您可以将一个函数声明为要在其中使用 await 的异步函数,然后在这些异步声明的函数中,您可以调用返回带有 await 的承诺的函数,而不是使用.then()它们的处理程序。这里没有神奇的捷径。从承诺设计开始。

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

// 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();
Run Code Online (Sandbox Code Playgroud)

而且,这里同样适用于使用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();
Run Code Online (Sandbox Code Playgroud)

这两个示例产生相同的输出和相同的输出时序,因此希望您可以看到从 promises 到 async/await 的映射。