【问题标题】:Node.JS - Return Promise Gives 'undefined' [duplicate]Node.JS - 返回承诺给出“未定义”[重复]
【发布时间】:2023-03-28 09:51:01
【问题描述】:

当我尝试调用这个 oauth-1.0 API 请求时,

const request = require('request');
const OAuth = require('oauth-1.0a');
const crypto = require('crypto');

function main(params) {
    // Dependencies
    // Initialize
    const oauth = OAuth({
        consumer: {
            key: '****',
            secret: '****'
        },
        signature_method: 'HMAC-SHA1',
        hash_function(base_string, key) {
            return crypto.createHmac('sha1', key).update(base_string).digest('base64');
        }
    });
    // Note: The token is optional for some requests
    const token = {
        key: '****',
        secret: '****'
    };

    const request_data = {
        url: 'http://****/rest/V1/products/12345',
        method: 'GET',
        //data: { status: 'Hello Ladies + Gentlemen, a signed OAuth request!' }
    };

    return new Promise((resolve, reject) => {
        request({
            url: request_data.url,
            method: request_data.method,
            form: request_data.data,
            headers: oauth.toHeader(oauth.authorize(request_data, token))
        }, function (err, res, body) {
            //console.log(res.body.name);
            if (err){ 
                reject({
                    statusCode: 500,
                    headers: { 'Content-Type': 'application/json' },
                    body: {'message': 'Error processing your request' },
                  });    
            } else {
                resolve({
                    body: JSON.parse(body),
                })
            }
        });
    });
};
exports.main = main;

它返回

承诺{ }

未定义

但是,当我只使用 console.log(body) 时,它会给出正确的结果

........

..................

....

.....

.....

.....

【问题讨论】:

  • 你必须等待.then回调中的promise解决。
  • 我遵循了 IBM Cloud Functions 天气模板的布局,它的布局与我的几乎完全相同(除了我的是 oauth 而天气不是)。我只是不确定为什么那个有效,但我的无效

标签: node.js promise return oauth-1.0a


【解决方案1】:

实际上它工作正常并返回 Promise。

所以如果你想从promise中获取“数据”,你应该使用Promise.then()

就像这个来自 MDN 的例子一样。

const promise1 = new Promise(function(resolve, reject) {
  resolve('Success!');
});

promise1.then(function(value) {
  console.log(value);
  // expected output: "Success!"
});

希望对你有帮助!

【讨论】:

  • 我不想使用 console.log。当我做'返回值'时,它仍然没有给出任何东西
  • 您可以在处理该承诺的地方发布代码吗?
  • 我将发布整个内容。
  • 我遵循的例子是:writeurl.com/text/vq2dpbckh93ndvo1aieg/0cw63gdn2eg6bpznc48i,它完美地工作
  • 我在这里看不到任何可能导致问题的东西。但仍不清楚您如何处理“main”函数的调用。
猜你喜欢
  • 2021-11-01
  • 2015-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-10
  • 1970-01-01
相关资源
最近更新 更多