使用async和await无法进行HTTP请求

3

尝试在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)

这是该脚本的源代码。
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();

Node.js 版本为 v8.4.0,运行在 Ubuntu 14.04 上。


async/await 不能神奇地与期望回调的函数一起工作。如果 client.get() 期望一个回调作为参数,那么如果你要使用它,你必须传递一个回调。async/await 与返回承诺的异步操作一起工作,并在这些承诺上操作。它们不能神奇地让你跳过传递回调到为回调设计的函数。我建议更多地阅读如何实际使用 asyncawait - jfriend00
一般来说,使用 async/await 的路径是首先设计所有异步操作以使用 promises 和 .then() 处理程序。然后,在所有这些都正常工作之后,您可以声明返回 promises 的函数为 async,然后您可以使用 await 调用这些函数,而不是使用 .then() 处理程序。这里没有任何魔法快捷方式。从 promise 设计开始。 - jfriend00
谢谢。所以,除非第三方函数专门为Promise设计,否则我们不能以这种方式使用它? - packetie
是的,那是正确的。async/await 与返回承诺的异步操作一起使用,而不是使用回调的异步操作。请阅读更多有关它们的内容并学习使用它们的代码示例。 - jfriend00
3个回答

5
async/await并不会自动适用于那些需要回调函数的函数。如果client.get()期望一个回调函数作为参数,那么你必须传递一个回调函数才能使用它。 async/await用于返回promise的异步操作,并且它们在这些promise上运行。它们不能让你跳过为回调而设计的函数的回调传递。建议您仔细阅读有关如何实际使用asyncawait的更多内容。
总体来说,实现async/await的路径是先将所有的async操作设计成使用promises和.then()处理程序。然后,在所有这些工作完成之后,您可以声明一个要使用await的async函数,然后在这些async声明的函数内部,您可以使用await而不是使用.then()处理程序来调用返回promises的函数。这里没有魔法捷径。从promise设计开始。
以下是一个简单的promise示例:
// 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();

这两个示例输出相同且输出时间相同,希望您能看到从 promises 到 async/await 的映射。


1

1
function clientRest(args) {
   return new Promise(resolve => {
      client.post("url", args, (data,response)=> {
        resolve(data)
      })
   })
}
let data_image = await clientRest(args)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接