我是 nodejs 的新手。我在 ex 1 中没有看到响应,但我在 ex 2 中看到了。为什么? Await 在其他地方为我工作,使用 babel。
前 1
let res = await request(url)
console.log(res);
console.log(res.body);
前 2
request(url, function (error, res, body) {
if (!error && response.statusCode == 200) {
console.log(body)
}
});
Await 在其他地方工作,我正在使用 babel 和 es6 和 es7 功能所需的模块。例如,我验证了 await 在 squelize 调用中工作。但它不适用于请求调用。为什么?
最佳答案
你应该只对返回 Promise 的东西 await
。在开始使用 async
和 await
之前,我绝对会推荐阅读 Promises。您可能可以通过围绕 request
创建自己的包装函数以使其返回 promise ,从而使该示例正常工作,如下所示:
function doRequest(url) {
return new Promise(function (resolve, reject) {
request(url, function (error, res, body) {
if (!error && res.statusCode === 200) {
resolve(body);
} else {
reject(error);
}
});
});
}
// Usage:
async function main() {
try {
let response = await doRequest(url);
console.log(response); // `response` will be whatever you passed to `resolve()` at the top
} catch (error) {
console.error(error); // `error` will be whatever you passed to `reject()` at the top
}
}
main();
编辑:或者,您可以考虑使用 a promise-based request library而不是常规的请求模块。
关于node.js - 为什么等待不适用于 Node 请求模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38428027/