在 NodeJS 的另一个函数中使用函数时出现 UnhandledPromiseRejectionWarning

UnhandledPromiseRejectionWarning when using a function inside another function in NodeJS

我正在使用 NodeJS 从 twitter 中提取原始 URL,我有以下功能

首先我提取推文并将其正文保存在一个变量中,如下所示

getTweets().then(tweets=>{
    let tweet = tweets[0].text;
    let tcoURL = extractURL(tweet); //this function extracts the t.co url from tweet using regex
    console.log(tcoURL)
    
    //but when I execute this following function, I'm getting unhandled promise error
    extractTransactionURL(tcoURL).then(url=>{
        console.log(url)
    })
})

extractTransactionURL函数如下,它取入t.courl和returns原来的url

const request = require('request')

function extractTransactionURL(url){

    let headers = {
        "User-Agent": "Please gimme back the original url from the tweet"
    }
  
    var options = {
      url, headers
    }
  
    return new Promise((resolve, reject)=>{
        setTimeout(()=>{
            request.get(options, function (error, resp, body) {
                    if (!error && resp.statusCode==200) {
                        resolve(resp.request.uri.href);
                    }
                    else{
                        reject(error)
                    }
                }
            ), 250})
    }); 
}

请帮忙,我们将不胜感激。

这是完整的错误

(node:4216) UnhandledPromiseRejectionWarning: null
(node:4216) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:4216) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

这可能不是因为嵌套函数而发生的,而是因为 .then()UnhandledPromiseRejectionWarning 当承诺失败时发生,并且您没有代码来处理拒绝。在这里,.then() 只有一个参数用于处理已履行的承诺,但您应该添加第二个参数,它是被拒绝承诺的回调(当承诺失败且未履行时会发生什么)。

基本上,在您的 extractTransactionURL(url) 函数中,我们最终调用了 reject(error) 的承诺 returns。但是,.then() 没有回调来处理拒绝并抛出警告。

您可以执行以下操作:

getTweets().then(tweets=>{
    let tweet = tweets[0].text;
    let tcoURL = extractURL(tweet); //this function extracts the t.co url from tweet using regex
    console.log(tcoURL)
    
    extractTransactionURL(tcoURL).then(url=>{
        console.log(url)
    }, err=>{
        // DO SOMETHING TO HANDLE UNFULFILLED PROMISE
    })
}, err=>{
    // DO SOMETHING TO HANDLE UNFULFILLED PROMISE
});