☆─────────────────────────────────────☆
aYong77 (aYong77) 于 (Fri May 19 15:21:02 2023) 提到:
在js里面。 XMLHttpRequest 用同步方式调用,然后返回网页内容。
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return xmlHttp.responseText;
}
但是在nodejs里面。是异步的方式获取网页内容
var req = http.request(option, function(res){
var rescont="";
res.setEncoding('utf8');
res.on('data', (chunk) => {
rescont+=chunk;
});
res.on('end', () => {
console.log(rescont);
});
})
req.on('error', (e) => {
reject('error');
});
req.end();
req发出去了,要等消息。
请问,怎么改写成第一种类似js的同步方式: 等到结果再return。而且能返回结果。
☆─────────────────────────────────────☆
ttl (小驴) 于 (Fri May 19 17:24:06 2023) 提到:
这都啥年代了,用fetch api呀,node/web通用。
async function foo() {
const resp = await fetch('
https://xxxxxx/api/json');
const json = await resp.json();
console.log(json);
}
要是不用async function,就是:
fetch('
https://xxxx/api/json')
.then(response => response.json())
.then(console.log)
【 在 aYong77 的大作中提到: 】
☆─────────────────────────────────────☆
hgoldfish (老鱼) 于 (Fri May 19 22:16:40 2023) 提到:
新时代是用 async 协程。
【 在 aYong77 的大作中提到: 】
☆─────────────────────────────────────☆
hgoldfish (老鱼) 于 (Fri May 19 22:17:28 2023) 提到:
前年我还在这里和一大票人争说 async 才是未来。当时好多人还在搞后一种回调式开发。
【 在 ttl 的大作中提到: 】
☆─────────────────────────────────────☆
ttl (小驴) 于 (Sat May 20 09:15:15 2023) 提到:
前年?他们这么落后于时代么,哈哈哈哈
【 在 hgoldfish 的大作中提到: 】
☆─────────────────────────────────────☆
aYong77 (aYong77) 于 (Sat May 20 20:51:01 2023) 提到:
【 在 ttl 的大作中提到: 】
谢谢。
如果 这个foo函数return一个变量
async function foo() {
const resp = await fetch('
https://xxxxxx/api/json');
const json = await resp.json();
return json;
}
function myfunc(){
let re = foo();
re.then( (res) => {
res 数据在这里,我想传到myfunc外面。
});
// return 这里没有数据。
}
我的问题是,如果我希望 myfunc返回 数据, 改怎么办? 数据只有 then 里面。
☆─────────────────────────────────────☆
ttl (小驴) 于 (Sun May 21 20:06:32 2023) 提到:
这是异步方法呀,你要么就用async function去处理,要么就传个回调,或者返回一个Promise。
【 在 aYong77 的大作中提到: 】
☆─────────────────────────────────────☆
aYong77 (aYong77) 于 (Mon May 22 00:54:39 2023) 提到:
【 在 ttl 的大作中提到: 】
也就是说,他毕竟不是同步的。
所以,只能用then???
☆─────────────────────────────────────☆
ttl (小驴) 于 (Mon May 22 14:38:15 2023) 提到:
所以推荐以async function为主呀
【 在 aYong77 的大作中提到: 】
☆─────────────────────────────────────☆
gmnicx (MR.Zhuang|5.1的新开始) 于 (Wed Jun 21 11:21:08 2023) 提到:
async 咋都5年前的东西了
【 在 hgoldfish 的大作中提到: 】