Nodejs 请求函数还没有完成但是代码进行到下一步?

Nodejs request function still not finished but code proceeds to the next step?

有点新的 nodejs,我似乎无法让我的回调函数工作。现在我的函数只想检查 URL 是否存在

const request = require('request')
const URL = 'http://sampleurl.com'
var urlexists = false

async _urlExists(URL){
    request(url, function (error, response, body) {
      if (!error && response.statusCode.toString()[0] === '2'){
        urlexists = true
      } else {
        throw new Error(`url is not working: ${URL}`)
      }
    })
  }  

问题是,我的代码继续执行下一个代码,这意味着 结果已通过 ,但几秒钟后,控制台显示抛出错误 url 不工作:${URL}.

基本上我只是打电话 await this._urlExists(URL)

_urlExists 函数在调用 request 后立即 returning,然后等待响应。 _urlExists 函数需要 return 一个 Promise,以便调用者知道数据何时准备就绪。

我查看了您正在使用的 request npm 包,如果不使用 request-promise-native 包装器包,它不支持 Promises。

但是,您仍然可以将 request 调用包装在 Promise 中:

async _urlExists(URL) {
    return new Promise((resolve, reject) => {
        request(url, function (error, response, body) {
            if (!error && response.statusCode.toString()[0] === '2'){
                urlexists = true;
                resolve(true);
            } else {
                reject(`url is not working: ${URL}`);
            }
        });
    });
}

现在,当您调用 await this._urlExists 时,该函数将暂停以等待 resolvereject 响应,然后再继续。要从可能的 reject 调用中捕获错误,请将 _urlExists 调用包装在 try-catch 块中。

还要确保您调用的函数 await this._urlExists 声明为 async,因为 await 关键字只能在 async 的函数内部使用.

如果您在实施我的解决方案时遇到任何问题或疑问,请在评论中告诉我。