Javascript 异步/等待永远卡住
编写一个使用async/await的webapp,但是在行Javascript 异步/等待永远卡住,javascript,asynchronous,Javascript,Asynchronous,编写一个使用async/await的webapp,但是在行var r1=await-fetch(url)的地方卡住了。然后((r)=>r.text())似乎永远在处理。我在端口80上侦听的web服务器甚至没有收到请求 const fetch = require ('fetch-node') const express = require('express'); const app = express(); var savedResolve; app.listen(8079, '127.0.0
var r1=await-fetch(url)的地方卡住了。然后((r)=>r.text())
似乎永远在处理。我在端口80上侦听的web服务器甚至没有收到请求
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
call的行附近添加try-and-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)
并且是两个不同的库
根据显示的代码,
节点fetch
是应该使用的库。将该行包装在try{}catch(e){}
中,并查看出现了什么错误(如果有)。哦,我不怎么使用fetch,但假设fetch()返回一个您不需要的承诺。然后(…)-r1的结果将是中的内容。然后((r)…)
谢谢@Deryck,我尝试了您的建议并得到了错误/堆栈跟踪。相应地更新了答案。谢谢。你可以尝试的一件事是使用不同的方式获取数据。这里的代码中没有对render
的引用,堆栈跟踪只是通过该模块。试试request-promise-native
——我在任何地方都使用它,而且我喜欢它。或者只使用本机节点http.get(URL)。根据显示的代码,您很可能希望使用库而不是。@t-niese这是一个很好的捕获!!我改为节点获取,效果很好!