【问题标题】:How can i use promise method in node我如何在节点中使用 promise 方法
【发布时间】:2021-02-18 06:04:43
【问题描述】:

我正在尝试 REST API 的 promise 函数,而不是使用 axios 方法。所以我可以等待结果,如果有任何错误。谁能帮我在node.js中将此代码更改为promise,以便我可以使用promise方法进行提取。谢谢

这是我的代码

const email = "xxx@xxxx.com"
function isUserExists(email, kc_accessToken) {
    let url = `${path}/users?email=${email}`;
    return axios_instance.get(url,
        {
            headers: {
                "content-type": "application/json",
                "authorization": `Bearer ${kc_accessToken}`
            }
        }).then(function (response) {
            if (response.data.length > 0) {
                return true;
            } else {
                return false;
            }
        })
        .catch(function (error) {
            console.log("some error occured");
        });
}


方法调用

http.createServer(function Test() {
    getAccessToken().then(function (response) {
        kc_accessToken = response.data.access_token;


        IsUserExists(email, kc_accessToken).then((resp) => {
            console.log(resp) 
            if(resp) {
                console.log("Do Not Create") 
         } else if (!resp) {
           console.log("Creat a new User")
          }


        })

    }).catch(function (error) {
        // handle error
        console.log(error);
    })
        .then(function () {
            // always executed
        });;
}).listen(8081);

【问题讨论】:

  • 您已经在该代码中使用了 Promise。究竟是什么问题,什么不起作用?

标签: node.js api rest promise request-promise


【解决方案1】:

我认为你需要这样的东西:

const email = "xxx@xxxx.com"
const request = require('request');
function isUserExists(email, kc_accessToken) {
    let url = `${path}/users?email=${email}`;

    return new Promise(function(resolve, reject){
        request({
            url: url,
            headers: {
                "content-type": "application/json",
                "authorization": `Bearer ${kc_accessToken}`
            }
        }, function (error, response, body) {
            if (error) {
                console.log("some error occured");
            }
            if (response.data.length > 0) {
                return resolve();
            }

            return reject();

        });
    });
}

【讨论】:

  • 非常感谢。但我在 resposne.data.length 有一个错误,它说长度未定义是 promise 函数的问题,因为在其他方法中它工作正常
  • 我认为您需要调查您的 response 对象中的内容。您可以添加 console.log(response) 并检查 data 是否放置在那里?也可能需要添加 JSON.parse(response).data.length
  • 我一定会调查的。我确实尝试过,它给了我 SyntaxError: Unexpected token o in JSON at position 1
  • 那么你需要检查response对象结构是什么,在调用response.data.length之前放置console.log(response)。
  • 我认为你使用这种结构不正确。你需要使用类似的东西:isUserExists().then(function(){console.log('user found')}, function(){console.log('user not found')})
猜你喜欢
  • 2021-05-11
  • 2021-08-29
  • 2017-02-23
  • 1970-01-01
  • 1970-01-01
  • 2019-10-19
  • 2019-01-09
  • 2018-10-24
  • 1970-01-01
相关资源
最近更新 更多