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

How can i use promise method in node

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

这是我的代码

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);

我想你需要这样的东西:

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();

        });
    });
}