如何在Node.js中的for循环中使用回调函数

时间:2019-05-02 20:16:01

标签: node.js

我定义了三个函数,它们都使用Promise返回一些值。第一个功能是通过调用数据库API返回令牌,第二个功能是使用从第一个函数返回的令牌返回所有数据库,第三个功能是使用前两个函数的信息获取帐户访问权限

function get_auth_token(){
    const  api_end_point = nebula_staging_url + "/api/v1/auth"

    var options = {
        url: api_end_point,
        headers: {"Content-Type": "application/json"},
        auth: {
            'user': 'admin',
            'pass': 'password'}
    }

    return new Promise((resolve, reject) => {
        request.get(options, function(error, response, body){
        if(!error && response.statusCode==200){
            var token = JSON.parse(body)
            var auth_token = token["data"][0]["accessToken"]
            // console.log(auth_token)
            resolve(auth_token)

        }
        else{
            reject(error)
        }
    })
})
}


function get_all_tenants(access_token){
    var api_end_point = nebula_staging_url + "/api/v1/tenants"

    var options = {
        url: api_end_point,
        headers: {
            "Content-Type": "application/json",
            "x-access-token": access_token
        },
        auth: {
            "user": "admin",
            "pass": "password"
        }
    }

    return new Promise((resolve, reject) => {
        request.get(options, function(error, response, body){
        if(!error && response.statusCode==200){
            var tenants = JSON.parse(body)
            resolve(tenants)

        }
        else{
            reject(error)
        }
    })
})
}


function get_account_access(tenant_id, access_token){
    var api_end_point = nebula_staging_url + "/api/v1/tenants/" + tenant_id + "/access"

    var options = {
        url: api_end_point,
        headers: {"Content-Type": "application/json", "x-access-token": access_token}
    }

    return new Promise((resolve, reject) => {
        request.get(options, function(error, response, body){
        if(!error && response.statusCode==200){
            try{
                var tenants = JSON.parse(body)
                //console.log(tenants)
                resolve(tenants)
            }
            catch(err){
                console.log(err)
            }
        }
        else{
            reject(error)
        }
    })
})
}

// Trying to print something info

get_auth_token().then(token => 
    get_all_tenants(token).then(tenants => {

        var count = 0 
        for(var i=0; j=tenants["data"].length,i<j; i++){

            if(tenants["data"][i]["name"].includes("PERF")){
                var tenant_id = tenants["data"][i]["id"]

                console.log("old_tenant_id", tenant_id)

                get_account_access(tenant_id, token).then(account_access => {

                    console.log("new_tenant_id", tenant_id)

                })
             }

       //break

       count = count + 1
       if(count==3){break}
    }

 }))

当我打印所有的old_tenant_id(在get_account_access函数之外)时,它会打印正确的,但new_tenant_id仅打印最后一个。输出看起来像这样:

enter image description here

似乎只有最后一个租户ID通过get_account_access函数。我对Node.js非常陌生,并且有使用回调函数的感觉,但是,我不知道如何在我的情况下实现它。请对我好一点:)

2 个答案:

答案 0 :(得分:0)

在这种情况下,您应该使用Promise.all来执行所有诺言。使用for循环创建一个可运行的promise数组,然后将它们全部一起运行(异步)。

let tenantsPromise = [] // array to hold promises

for(var i=0; j=tenants["data"].length,i<j; i++){

            if(tenants["data"][i]["name"].includes("PERF")){
                var tenant_id = tenants["data"][i]["id"]

                console.log("old_tenant_id", tenant_id)
                tenantsPromise.push()
                get_account_access(tenant_id, token).then(account_access => {
                    console.log("new_tenant_id", tenant_id)
                    return tenant_id // return the new id
                })) // push your promises into the array
             }
            }

// and then run all of the promises at one time
Promise.all(tenantsPromise).then(function(new_ids){
    console.log(new_ids)

    // here you can do a for loop and see if the results are the same
    for(var i=0; j=tenants["data"].length,i<j; i++){

            if(tenants["data"][i]["name"].includes("PERF")){
                var tenant_id = tenants["data"][i]["id"]
                var new_id = new_ids["data"][i]["id"]
                console.log(`Ids equal? ${tenant_id===new_id}`)
           }

})

签出Promise.all()文档。

答案 1 :(得分:0)

For loop with Node js promise chaining

这篇文章解决了我的问题,只要我使用let代替var,new_tenant_id将与old_tenant_id相同