我在这里对 Promise 拒绝做错了什么?

What am i doing wrong with Promise rejections here?

所以我在这里为节点制作了一些可重用的代码,并且我通过异步/等待来应用它。尽管我确定在使用此代码时我在这里误解了很多......但是,我发誓,我有一个项目我正在使用它工作的代码,而另一个项目则没有。 我正在使用 requestrequest-promise.

UrlRequest: function( opts ) {
    return new Promise( (resolve, reject) => {
        request( opts, 
            function(error, request, body) {
                if (error) 
                    reject( {error: true, msg: error} );
                else
                    resolve( {body, request} );
            });
        })
        .catch(err => reject( {error: true, msg: err} ));
    }

我相当确定 .catch() 是错误的。但它在我的第一个项目中没有出错。所以我想找出这样做的正确方法。我浏览过的几篇文章是我想出这个函数供使用的地方。我也知道如果真的发生任何错误(包括这种情况),它会抛出 UnhandledPromiseRejectionWarning 错误。那么如何妥善处理呢?

我如何使用它:

(async () => {
var result = await Promise.UrlRequest( {
    url: "...",
    method: "GET",
    headers: DefaultHeaders
    } );

// do stuff with result... 

}) ();

使用 request-promise,您无需编写自己的 Promise 包装器

// make sure you're using the promise version
const request = require('request-promise')

var opts = {
  ...
  resolveWithFullResponse: true    //  <---  <--- to get full response, response.body contains the body
};

// if you dont plan to use UrlRequest as constructor, better name is starting with lowercase: urlRequest, some naming convention
UrlRequest: async function( opts ) {
  let res;
  try {
    res = await request(opts);
  } catch (e) {
    // handle error
    throw e
  }
  return res;
}

注意:async 函数将 return 包装在 Promise

因为您已经安装了 request-promise,所以您不需要像现在这样构建 Promise。只需使用 it 而不是 request 然后你就会得到一个承诺。与此类似的东西应该可以工作:

const request = require('request-promise')

request(opts)
    .then((res) => {
        // Process res...
    })
    .catch((err) => {
        // Handle error...
    });

您可以继续将其包装在您的 UrlRequest 函数中并与 async 一起使用,如下所示:

UrlRequest: async ( opts ) => {
  try {
    const response = await request(opts);
    return response;
  } catch (error) {
    // Handle error
  }
}

如果您想使用then()catch(),您可以这样做:

UrlRequest: ( opts ) => {
  return request(opts)
            .then(response => response)
            .catch (error) {
              // Handle error
            }
}