gpt4 book ai didi

javascript - 如何在继续程序之前等待响应? (Nodejs 与 Elasticsearch)

转载 作者:行者123 更新时间:2023-12-03 06:44:15 25 4
gpt4 key购买 nike

我有一个名为 getFormattedURI(uri) 的方法,它接收 URI 并解析它以获取网站名称和查询等内容。此方法向 URI 发送请求并处理响应。但是,我希望 getFormattedURI(uri) 之后的所有代码都等待该方法完成,因为我在以下代码中使用该方法的返回值。它是这样的:

function getFormattedURI(uri) {
request.get(uri).end((err, res) => {
//(using superagent request) do stuff with res and return parsed uri
});
}

...
let x = getFormattedURI('www.google.com');
//do stuff with x like index it into Elasticsearch

我希望我的代码等待,直到收到请求的响应,而不是立即跳过函数调用。我如何实现这一目标?

最佳答案

阻塞(同步)JS线程被认为是非常糟糕的做法,而您的情况使用回调非常简单直接。

如果你想变得更花哨,你可以使用promise(前提是JS引擎支持promise,否则你应该使用第三方库)

使用 promise 的示例:

function getFormattedURI() {
return new Promise(function(resolve, reject) {
request.get(uri).end((err, res) => {
//(using superagent request) do stuff with res and return parsed uri
resolve(res);
});
});
}


getFormattedURI('www.google.com').then(function(res) {

})

关于javascript - 如何在继续程序之前等待响应? (Nodejs 与 Elasticsearch),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37819900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com