异步/等待永远卡住了

6

我正在编写一个使用async/await的web应用程序,但在出现var r1 = await fetch(url).then((r) => r.text())这行代码时发现它似乎一直在等待中。我的Web服务器监听端口80甚至没有收到请求。

const fetch = require ('fetch-node')
const express = require('express');
const app = express();

var savedResolve;

app.listen(8079, '127.0.0.1', function() {
    console.log('listening on 8079')
})
app.get('/*', async function (req, res) {
    console.log(req.path)
    res.setHeader('Content-Type', 'text/html');
    await task()
    res.send('Done')
})


async function task() {
    console.log("starting..")
    var url = "http://localhost/prod/te.php";
    var r1 = await fetch(url).then((r) => r.text())
    console.log(r1)
    return "done"
}

有什么想法吗?谢谢提前!

更新1

感谢@deryck的建议,在fetch调用的行周围添加了try和catch,得到了以下错误

TypeError: Cannot read property 'render' of undefined
    at module.exports (/Users/jsmith/learn/node/node_modules/hooks-node/hooks-node.js:8:11)
    at module.exports (/Users/jsmith/learn/node/node_modules/fetch-node/fetch-node.js:17:1)
    at task (/Users/jsmith/learn/node/te4b.js:22:18)
    at /Users/jsmith/learn/node/te4b.js:13:8
    at Layer.handle [as handle_request] (/Users/jsmith/learn/node/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/jsmith/learn/node/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/Users/jsmith/learn/node/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/Users/jsmith/learn/node/node_modules/express/lib/router/layer.js:95:5)
    at /Users/jsmith/learn/node/node_modules/express/lib/router/index.js:281:22
    at param (/Users/jsmith/learn/node/node_modules/express/lib/router/index.js:354:14)

你可以尝试使用不同的方式获取数据。在你的代码中没有对render的引用,而且堆栈跟踪只是通过该模块。尝试使用request-promise-native - 我在任何地方都使用它并喜欢它。或者只需使用本机的node http.get(URL)。 - Deryck
根据所示代码,您最有可能想要使用库node-fetch,而不是fetch-node - t.niese
你在使用fetch-node做什么? - Prajval M
1
@t-niese,太棒了!我改用node-fetch后,它运行得很好! - pktCoder
@t-niese 提到的 try/catch 很有道理。我会去了解一下 Koa。再次感谢。 - pktCoder
显示剩余5条评论
1个回答

3

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