我如何在节点中使用Promise方法

问题描述

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

这是我的代码

const email = "[email protected]"
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);

解决方法

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

const email = "[email protected]"
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();

        });
    });
}