Nodejs Promise not resolving/no data returned











up vote
0
down vote

favorite












I have a promise function that makes two request calls and resolves after the second call is done. The second resolve call also depends on the data from the first call. But in the then function, i am getting null for the variable return. Any help would be appreciated.



Edit: secResp.body has the correct data, it is not null



const express = require('express');
const request = require('request');
const app = express();
const port = process.env.PORT || 5000;

// console.log that your server is up and running
app.listen(port, () => console.log(`Listening on port ${port}`));

app.get('/api/currentMatch/:name', function(req, res, next){
getPlayersInMatch(req.params.name).then(function(participants){
//this is null
console.log(participants);
}).catch(function (err) {
console.log(err);
});
})

function getPlayersInMatch(name){
return new Promise(function(resolve, reject){
request.get({
url: api_url
}, function(firstErr, firstResp, body){
if(firstResp.StatusCode != 200){
reject(firstErr);
}
var accountId = JSON.parse(firstResp.body).id;
request.get({
url: api_url2 + 'accountId=' + accountId
}, function(secErr, secResp, body){
if(secResp.StatusCode != 200){
reject(secErr);
}
//this is not null, this is an array
var participants = JSON.parse(secResp.body).participants;
resolve(participants);
});
});
});
}









share|improve this question




















  • 1




    Sounds like the participants property of the secResp.body is null.
    – CertainPerformance
    Nov 11 at 1:42










  • add a 'retiurn' ..... return getPlayersInMatch(req.params.name).then ....
    – Robert Rowntree
    Nov 11 at 1:46










  • @RobertRowntree - how does that effect the value of participants result in .then(function(participants)
    – Bravo
    Nov 11 at 1:51












  • this is an array - what is an array? JSON.parse(secResp.body)? if so, then it's never going to have .participants property, because arrays do not. While you CAN add any property you like to an array, since the array is "created" by JSON.parse, it's never going to have a custom property
    – Bravo
    Nov 11 at 1:54










  • debug step 1 ... console.log(secResp.body) - add the output to the question
    – Bravo
    Nov 11 at 1:55















up vote
0
down vote

favorite












I have a promise function that makes two request calls and resolves after the second call is done. The second resolve call also depends on the data from the first call. But in the then function, i am getting null for the variable return. Any help would be appreciated.



Edit: secResp.body has the correct data, it is not null



const express = require('express');
const request = require('request');
const app = express();
const port = process.env.PORT || 5000;

// console.log that your server is up and running
app.listen(port, () => console.log(`Listening on port ${port}`));

app.get('/api/currentMatch/:name', function(req, res, next){
getPlayersInMatch(req.params.name).then(function(participants){
//this is null
console.log(participants);
}).catch(function (err) {
console.log(err);
});
})

function getPlayersInMatch(name){
return new Promise(function(resolve, reject){
request.get({
url: api_url
}, function(firstErr, firstResp, body){
if(firstResp.StatusCode != 200){
reject(firstErr);
}
var accountId = JSON.parse(firstResp.body).id;
request.get({
url: api_url2 + 'accountId=' + accountId
}, function(secErr, secResp, body){
if(secResp.StatusCode != 200){
reject(secErr);
}
//this is not null, this is an array
var participants = JSON.parse(secResp.body).participants;
resolve(participants);
});
});
});
}









share|improve this question




















  • 1




    Sounds like the participants property of the secResp.body is null.
    – CertainPerformance
    Nov 11 at 1:42










  • add a 'retiurn' ..... return getPlayersInMatch(req.params.name).then ....
    – Robert Rowntree
    Nov 11 at 1:46










  • @RobertRowntree - how does that effect the value of participants result in .then(function(participants)
    – Bravo
    Nov 11 at 1:51












  • this is an array - what is an array? JSON.parse(secResp.body)? if so, then it's never going to have .participants property, because arrays do not. While you CAN add any property you like to an array, since the array is "created" by JSON.parse, it's never going to have a custom property
    – Bravo
    Nov 11 at 1:54










  • debug step 1 ... console.log(secResp.body) - add the output to the question
    – Bravo
    Nov 11 at 1:55













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I have a promise function that makes two request calls and resolves after the second call is done. The second resolve call also depends on the data from the first call. But in the then function, i am getting null for the variable return. Any help would be appreciated.



Edit: secResp.body has the correct data, it is not null



const express = require('express');
const request = require('request');
const app = express();
const port = process.env.PORT || 5000;

// console.log that your server is up and running
app.listen(port, () => console.log(`Listening on port ${port}`));

app.get('/api/currentMatch/:name', function(req, res, next){
getPlayersInMatch(req.params.name).then(function(participants){
//this is null
console.log(participants);
}).catch(function (err) {
console.log(err);
});
})

function getPlayersInMatch(name){
return new Promise(function(resolve, reject){
request.get({
url: api_url
}, function(firstErr, firstResp, body){
if(firstResp.StatusCode != 200){
reject(firstErr);
}
var accountId = JSON.parse(firstResp.body).id;
request.get({
url: api_url2 + 'accountId=' + accountId
}, function(secErr, secResp, body){
if(secResp.StatusCode != 200){
reject(secErr);
}
//this is not null, this is an array
var participants = JSON.parse(secResp.body).participants;
resolve(participants);
});
});
});
}









share|improve this question















I have a promise function that makes two request calls and resolves after the second call is done. The second resolve call also depends on the data from the first call. But in the then function, i am getting null for the variable return. Any help would be appreciated.



Edit: secResp.body has the correct data, it is not null



const express = require('express');
const request = require('request');
const app = express();
const port = process.env.PORT || 5000;

// console.log that your server is up and running
app.listen(port, () => console.log(`Listening on port ${port}`));

app.get('/api/currentMatch/:name', function(req, res, next){
getPlayersInMatch(req.params.name).then(function(participants){
//this is null
console.log(participants);
}).catch(function (err) {
console.log(err);
});
})

function getPlayersInMatch(name){
return new Promise(function(resolve, reject){
request.get({
url: api_url
}, function(firstErr, firstResp, body){
if(firstResp.StatusCode != 200){
reject(firstErr);
}
var accountId = JSON.parse(firstResp.body).id;
request.get({
url: api_url2 + 'accountId=' + accountId
}, function(secErr, secResp, body){
if(secResp.StatusCode != 200){
reject(secErr);
}
//this is not null, this is an array
var participants = JSON.parse(secResp.body).participants;
resolve(participants);
});
});
});
}






javascript node.js promise request






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 11 at 1:54

























asked Nov 11 at 1:39









dest

205




205








  • 1




    Sounds like the participants property of the secResp.body is null.
    – CertainPerformance
    Nov 11 at 1:42










  • add a 'retiurn' ..... return getPlayersInMatch(req.params.name).then ....
    – Robert Rowntree
    Nov 11 at 1:46










  • @RobertRowntree - how does that effect the value of participants result in .then(function(participants)
    – Bravo
    Nov 11 at 1:51












  • this is an array - what is an array? JSON.parse(secResp.body)? if so, then it's never going to have .participants property, because arrays do not. While you CAN add any property you like to an array, since the array is "created" by JSON.parse, it's never going to have a custom property
    – Bravo
    Nov 11 at 1:54










  • debug step 1 ... console.log(secResp.body) - add the output to the question
    – Bravo
    Nov 11 at 1:55














  • 1




    Sounds like the participants property of the secResp.body is null.
    – CertainPerformance
    Nov 11 at 1:42










  • add a 'retiurn' ..... return getPlayersInMatch(req.params.name).then ....
    – Robert Rowntree
    Nov 11 at 1:46










  • @RobertRowntree - how does that effect the value of participants result in .then(function(participants)
    – Bravo
    Nov 11 at 1:51












  • this is an array - what is an array? JSON.parse(secResp.body)? if so, then it's never going to have .participants property, because arrays do not. While you CAN add any property you like to an array, since the array is "created" by JSON.parse, it's never going to have a custom property
    – Bravo
    Nov 11 at 1:54










  • debug step 1 ... console.log(secResp.body) - add the output to the question
    – Bravo
    Nov 11 at 1:55








1




1




Sounds like the participants property of the secResp.body is null.
– CertainPerformance
Nov 11 at 1:42




Sounds like the participants property of the secResp.body is null.
– CertainPerformance
Nov 11 at 1:42












add a 'retiurn' ..... return getPlayersInMatch(req.params.name).then ....
– Robert Rowntree
Nov 11 at 1:46




add a 'retiurn' ..... return getPlayersInMatch(req.params.name).then ....
– Robert Rowntree
Nov 11 at 1:46












@RobertRowntree - how does that effect the value of participants result in .then(function(participants)
– Bravo
Nov 11 at 1:51






@RobertRowntree - how does that effect the value of participants result in .then(function(participants)
– Bravo
Nov 11 at 1:51














this is an array - what is an array? JSON.parse(secResp.body)? if so, then it's never going to have .participants property, because arrays do not. While you CAN add any property you like to an array, since the array is "created" by JSON.parse, it's never going to have a custom property
– Bravo
Nov 11 at 1:54




this is an array - what is an array? JSON.parse(secResp.body)? if so, then it's never going to have .participants property, because arrays do not. While you CAN add any property you like to an array, since the array is "created" by JSON.parse, it's never going to have a custom property
– Bravo
Nov 11 at 1:54












debug step 1 ... console.log(secResp.body) - add the output to the question
– Bravo
Nov 11 at 1:55




debug step 1 ... console.log(secResp.body) - add the output to the question
– Bravo
Nov 11 at 1:55












3 Answers
3






active

oldest

votes

















up vote
1
down vote



accepted










I rewrote your code for request-promise. The main issue I found with your code is that it's too complicated. Simplifying things makes it easier to find what you did wrong.



const rp = require('request-promise')
const app = express();
const port = process.env.PORT || 5000;

// console.log that your server is up and running
app.listen(port, () => console.log(`Listening on port ${port}`));

app.get('/api/currentMatch/:name', function(req, res, next){
getPlayersInMatch(req.params.name)
.then(console.log)
.catch(console.error)
})

const getPlayersInMatch = async name => {
const id = await rp(api_url)
.then(res => JSON.parse(res.body).id)

const participants = await rp(api_url2 + 'accountId=' + accountId)
.then(res => JSON.parse(res.body).participants)

return { id, participants }
}





share|improve this answer























  • Thanks, i switched to using request promise and it seems to be working.
    – dest
    Nov 11 at 3:45


















up vote
0
down vote













function getPlayersInMatch(name){
return new Promise(async function(resolve, reject){
return await request.get({
url: api_url
}, function(firstErr, firstResp, body){
if(firstResp.StatusCode != 200){
reject(firstErr);
}
var accountId = JSON.parse(firstResp.body).id;
request.get({
url: api_url2 + 'accountId=' + accountId
}, function(secErr, secResp, body){
if(secResp.StatusCode != 200){
reject(secErr);
}
//this is an array
var participants = JSON.parse(secResp.body).participants;
resolve(participants);
});
});
});
}


try it.



one, you shoule return request result or object.
two, you should use async await because its not wait to request data in async callback.






share|improve this answer





















  • you shoule return request result and you should use async await disagree - because you are using it to await a promise inside a promise executor which makes absolutely less sense than the original code - and since request.get doesn't return a promise, there's absolutely no point to await it
    – Bravo
    Nov 11 at 1:56












  • Oh you right. Thank you
    – 곽대용
    Nov 11 at 1:59


















up vote
0
down vote













In your code, it's hard to find out which step gets error.



I think it's better to wrap request module like:



/**
* Mapping knowing error_code
* @param {Number} error_code
* @param {String} msg
*/
function error_def(error_code, msg) {
let status, message;
switch(error_code){
case 400:
case 401:
case 402:
case 403:
case 1000:
case 1001:
case 1002:
case 1003:
case 1005:
status = error_code;
message = msg;
break;
default:
status = 2000;
message = 'Undefined Error'
}
return {status: status, msg: message};
}

/**
* Generate error message
* @param {String} tag
* @param {Number} error_code
* @param {String} msg
*/
function gen_error_func(tag = null) {
return function(error_code, msg = null) {
return {tag: tag, error_message: error_def(error_code, msg)}
}
}

/**
* Wrap the request and return interesting keys
* @param {String} tag
* @param {Object} req_opt
* @param {Array} interesting_resp
* @return {Object}
*/

function req_wrap(tag = null, req_opt, interesting_resp = null){
return new Promise((resolve, reject) => {
let gen_error = gen_error_func(tag)

if (!req_opt.url) {
reject(gen_error(1000, 'missing url'));
}

let option = {
url: req_opt.url,
method: (req_opt.method)? req_opt.method: 'GET',
}

request(option, function(error, response, body) {
if(error) {
reject(gen_error(1001, error));
return;
}

if (!response) {
reject(gen_error(1005, 'response is undefine, maybe wrong url!'))
return;
}

if (response.statusCode >= 400) {
//http level error
reject(gen_error(response.statusCode, body));
}else {
let result = {};
let body_json;
try {
body_json = JSON.parse(body);
}catch(e) {
reject(gen_error(1002, `Unknow response: ${body}`))
}
if (interesting_resp) {
interesting_resp.map(key => {
if (body_json[key] == undefined) {
reject(gen_error(1003, `In ${body_json}, undefined ${key}`))
return;
}
result[key] = body_json[key];
})
}else {
result = body_json;
}
resolve(result);
}
})
})
}



  • req_wrap:


    • Parameters



      • tag: Showing the request you define, ex: 'first connection'


      • req_opt: request option


      • interesting_resp: the keys what you're interesting






NOTE: In req_wrap, if it cannot find the key in interesting_resp in response (undefined or null) the function will reject. It's necessary to check the server's spec you request!



You can rewrite your code:



function getPlayersInMatch(name){
return new Promise(function(resolve, reject){
req_wrap('first_conn', {url: api_url}, ['id']).then(result => {
req_wrap('second_conn', {url: api_url2 + 'accountId=' + result.id}, ['participants']).then(result => {
resolve(result.participants)
}).catch(error => {
reject(error)
})
}).catch(error => {
reject(error)
})
});
}


Now it's more clear to check which step is wrong.






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53245123%2fnodejs-promise-not-resolving-no-data-returned%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote



    accepted










    I rewrote your code for request-promise. The main issue I found with your code is that it's too complicated. Simplifying things makes it easier to find what you did wrong.



    const rp = require('request-promise')
    const app = express();
    const port = process.env.PORT || 5000;

    // console.log that your server is up and running
    app.listen(port, () => console.log(`Listening on port ${port}`));

    app.get('/api/currentMatch/:name', function(req, res, next){
    getPlayersInMatch(req.params.name)
    .then(console.log)
    .catch(console.error)
    })

    const getPlayersInMatch = async name => {
    const id = await rp(api_url)
    .then(res => JSON.parse(res.body).id)

    const participants = await rp(api_url2 + 'accountId=' + accountId)
    .then(res => JSON.parse(res.body).participants)

    return { id, participants }
    }





    share|improve this answer























    • Thanks, i switched to using request promise and it seems to be working.
      – dest
      Nov 11 at 3:45















    up vote
    1
    down vote



    accepted










    I rewrote your code for request-promise. The main issue I found with your code is that it's too complicated. Simplifying things makes it easier to find what you did wrong.



    const rp = require('request-promise')
    const app = express();
    const port = process.env.PORT || 5000;

    // console.log that your server is up and running
    app.listen(port, () => console.log(`Listening on port ${port}`));

    app.get('/api/currentMatch/:name', function(req, res, next){
    getPlayersInMatch(req.params.name)
    .then(console.log)
    .catch(console.error)
    })

    const getPlayersInMatch = async name => {
    const id = await rp(api_url)
    .then(res => JSON.parse(res.body).id)

    const participants = await rp(api_url2 + 'accountId=' + accountId)
    .then(res => JSON.parse(res.body).participants)

    return { id, participants }
    }





    share|improve this answer























    • Thanks, i switched to using request promise and it seems to be working.
      – dest
      Nov 11 at 3:45













    up vote
    1
    down vote



    accepted







    up vote
    1
    down vote



    accepted






    I rewrote your code for request-promise. The main issue I found with your code is that it's too complicated. Simplifying things makes it easier to find what you did wrong.



    const rp = require('request-promise')
    const app = express();
    const port = process.env.PORT || 5000;

    // console.log that your server is up and running
    app.listen(port, () => console.log(`Listening on port ${port}`));

    app.get('/api/currentMatch/:name', function(req, res, next){
    getPlayersInMatch(req.params.name)
    .then(console.log)
    .catch(console.error)
    })

    const getPlayersInMatch = async name => {
    const id = await rp(api_url)
    .then(res => JSON.parse(res.body).id)

    const participants = await rp(api_url2 + 'accountId=' + accountId)
    .then(res => JSON.parse(res.body).participants)

    return { id, participants }
    }





    share|improve this answer














    I rewrote your code for request-promise. The main issue I found with your code is that it's too complicated. Simplifying things makes it easier to find what you did wrong.



    const rp = require('request-promise')
    const app = express();
    const port = process.env.PORT || 5000;

    // console.log that your server is up and running
    app.listen(port, () => console.log(`Listening on port ${port}`));

    app.get('/api/currentMatch/:name', function(req, res, next){
    getPlayersInMatch(req.params.name)
    .then(console.log)
    .catch(console.error)
    })

    const getPlayersInMatch = async name => {
    const id = await rp(api_url)
    .then(res => JSON.parse(res.body).id)

    const participants = await rp(api_url2 + 'accountId=' + accountId)
    .then(res => JSON.parse(res.body).participants)

    return { id, participants }
    }






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 11 at 2:15

























    answered Nov 11 at 2:07









    Besto

    899




    899












    • Thanks, i switched to using request promise and it seems to be working.
      – dest
      Nov 11 at 3:45


















    • Thanks, i switched to using request promise and it seems to be working.
      – dest
      Nov 11 at 3:45
















    Thanks, i switched to using request promise and it seems to be working.
    – dest
    Nov 11 at 3:45




    Thanks, i switched to using request promise and it seems to be working.
    – dest
    Nov 11 at 3:45












    up vote
    0
    down vote













    function getPlayersInMatch(name){
    return new Promise(async function(resolve, reject){
    return await request.get({
    url: api_url
    }, function(firstErr, firstResp, body){
    if(firstResp.StatusCode != 200){
    reject(firstErr);
    }
    var accountId = JSON.parse(firstResp.body).id;
    request.get({
    url: api_url2 + 'accountId=' + accountId
    }, function(secErr, secResp, body){
    if(secResp.StatusCode != 200){
    reject(secErr);
    }
    //this is an array
    var participants = JSON.parse(secResp.body).participants;
    resolve(participants);
    });
    });
    });
    }


    try it.



    one, you shoule return request result or object.
    two, you should use async await because its not wait to request data in async callback.






    share|improve this answer





















    • you shoule return request result and you should use async await disagree - because you are using it to await a promise inside a promise executor which makes absolutely less sense than the original code - and since request.get doesn't return a promise, there's absolutely no point to await it
      – Bravo
      Nov 11 at 1:56












    • Oh you right. Thank you
      – 곽대용
      Nov 11 at 1:59















    up vote
    0
    down vote













    function getPlayersInMatch(name){
    return new Promise(async function(resolve, reject){
    return await request.get({
    url: api_url
    }, function(firstErr, firstResp, body){
    if(firstResp.StatusCode != 200){
    reject(firstErr);
    }
    var accountId = JSON.parse(firstResp.body).id;
    request.get({
    url: api_url2 + 'accountId=' + accountId
    }, function(secErr, secResp, body){
    if(secResp.StatusCode != 200){
    reject(secErr);
    }
    //this is an array
    var participants = JSON.parse(secResp.body).participants;
    resolve(participants);
    });
    });
    });
    }


    try it.



    one, you shoule return request result or object.
    two, you should use async await because its not wait to request data in async callback.






    share|improve this answer





















    • you shoule return request result and you should use async await disagree - because you are using it to await a promise inside a promise executor which makes absolutely less sense than the original code - and since request.get doesn't return a promise, there's absolutely no point to await it
      – Bravo
      Nov 11 at 1:56












    • Oh you right. Thank you
      – 곽대용
      Nov 11 at 1:59













    up vote
    0
    down vote










    up vote
    0
    down vote









    function getPlayersInMatch(name){
    return new Promise(async function(resolve, reject){
    return await request.get({
    url: api_url
    }, function(firstErr, firstResp, body){
    if(firstResp.StatusCode != 200){
    reject(firstErr);
    }
    var accountId = JSON.parse(firstResp.body).id;
    request.get({
    url: api_url2 + 'accountId=' + accountId
    }, function(secErr, secResp, body){
    if(secResp.StatusCode != 200){
    reject(secErr);
    }
    //this is an array
    var participants = JSON.parse(secResp.body).participants;
    resolve(participants);
    });
    });
    });
    }


    try it.



    one, you shoule return request result or object.
    two, you should use async await because its not wait to request data in async callback.






    share|improve this answer












    function getPlayersInMatch(name){
    return new Promise(async function(resolve, reject){
    return await request.get({
    url: api_url
    }, function(firstErr, firstResp, body){
    if(firstResp.StatusCode != 200){
    reject(firstErr);
    }
    var accountId = JSON.parse(firstResp.body).id;
    request.get({
    url: api_url2 + 'accountId=' + accountId
    }, function(secErr, secResp, body){
    if(secResp.StatusCode != 200){
    reject(secErr);
    }
    //this is an array
    var participants = JSON.parse(secResp.body).participants;
    resolve(participants);
    });
    });
    });
    }


    try it.



    one, you shoule return request result or object.
    two, you should use async await because its not wait to request data in async callback.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 11 at 1:45









    곽대용

    455




    455












    • you shoule return request result and you should use async await disagree - because you are using it to await a promise inside a promise executor which makes absolutely less sense than the original code - and since request.get doesn't return a promise, there's absolutely no point to await it
      – Bravo
      Nov 11 at 1:56












    • Oh you right. Thank you
      – 곽대용
      Nov 11 at 1:59


















    • you shoule return request result and you should use async await disagree - because you are using it to await a promise inside a promise executor which makes absolutely less sense than the original code - and since request.get doesn't return a promise, there's absolutely no point to await it
      – Bravo
      Nov 11 at 1:56












    • Oh you right. Thank you
      – 곽대용
      Nov 11 at 1:59
















    you shoule return request result and you should use async await disagree - because you are using it to await a promise inside a promise executor which makes absolutely less sense than the original code - and since request.get doesn't return a promise, there's absolutely no point to await it
    – Bravo
    Nov 11 at 1:56






    you shoule return request result and you should use async await disagree - because you are using it to await a promise inside a promise executor which makes absolutely less sense than the original code - and since request.get doesn't return a promise, there's absolutely no point to await it
    – Bravo
    Nov 11 at 1:56














    Oh you right. Thank you
    – 곽대용
    Nov 11 at 1:59




    Oh you right. Thank you
    – 곽대용
    Nov 11 at 1:59










    up vote
    0
    down vote













    In your code, it's hard to find out which step gets error.



    I think it's better to wrap request module like:



    /**
    * Mapping knowing error_code
    * @param {Number} error_code
    * @param {String} msg
    */
    function error_def(error_code, msg) {
    let status, message;
    switch(error_code){
    case 400:
    case 401:
    case 402:
    case 403:
    case 1000:
    case 1001:
    case 1002:
    case 1003:
    case 1005:
    status = error_code;
    message = msg;
    break;
    default:
    status = 2000;
    message = 'Undefined Error'
    }
    return {status: status, msg: message};
    }

    /**
    * Generate error message
    * @param {String} tag
    * @param {Number} error_code
    * @param {String} msg
    */
    function gen_error_func(tag = null) {
    return function(error_code, msg = null) {
    return {tag: tag, error_message: error_def(error_code, msg)}
    }
    }

    /**
    * Wrap the request and return interesting keys
    * @param {String} tag
    * @param {Object} req_opt
    * @param {Array} interesting_resp
    * @return {Object}
    */

    function req_wrap(tag = null, req_opt, interesting_resp = null){
    return new Promise((resolve, reject) => {
    let gen_error = gen_error_func(tag)

    if (!req_opt.url) {
    reject(gen_error(1000, 'missing url'));
    }

    let option = {
    url: req_opt.url,
    method: (req_opt.method)? req_opt.method: 'GET',
    }

    request(option, function(error, response, body) {
    if(error) {
    reject(gen_error(1001, error));
    return;
    }

    if (!response) {
    reject(gen_error(1005, 'response is undefine, maybe wrong url!'))
    return;
    }

    if (response.statusCode >= 400) {
    //http level error
    reject(gen_error(response.statusCode, body));
    }else {
    let result = {};
    let body_json;
    try {
    body_json = JSON.parse(body);
    }catch(e) {
    reject(gen_error(1002, `Unknow response: ${body}`))
    }
    if (interesting_resp) {
    interesting_resp.map(key => {
    if (body_json[key] == undefined) {
    reject(gen_error(1003, `In ${body_json}, undefined ${key}`))
    return;
    }
    result[key] = body_json[key];
    })
    }else {
    result = body_json;
    }
    resolve(result);
    }
    })
    })
    }



    • req_wrap:


      • Parameters



        • tag: Showing the request you define, ex: 'first connection'


        • req_opt: request option


        • interesting_resp: the keys what you're interesting






    NOTE: In req_wrap, if it cannot find the key in interesting_resp in response (undefined or null) the function will reject. It's necessary to check the server's spec you request!



    You can rewrite your code:



    function getPlayersInMatch(name){
    return new Promise(function(resolve, reject){
    req_wrap('first_conn', {url: api_url}, ['id']).then(result => {
    req_wrap('second_conn', {url: api_url2 + 'accountId=' + result.id}, ['participants']).then(result => {
    resolve(result.participants)
    }).catch(error => {
    reject(error)
    })
    }).catch(error => {
    reject(error)
    })
    });
    }


    Now it's more clear to check which step is wrong.






    share|improve this answer

























      up vote
      0
      down vote













      In your code, it's hard to find out which step gets error.



      I think it's better to wrap request module like:



      /**
      * Mapping knowing error_code
      * @param {Number} error_code
      * @param {String} msg
      */
      function error_def(error_code, msg) {
      let status, message;
      switch(error_code){
      case 400:
      case 401:
      case 402:
      case 403:
      case 1000:
      case 1001:
      case 1002:
      case 1003:
      case 1005:
      status = error_code;
      message = msg;
      break;
      default:
      status = 2000;
      message = 'Undefined Error'
      }
      return {status: status, msg: message};
      }

      /**
      * Generate error message
      * @param {String} tag
      * @param {Number} error_code
      * @param {String} msg
      */
      function gen_error_func(tag = null) {
      return function(error_code, msg = null) {
      return {tag: tag, error_message: error_def(error_code, msg)}
      }
      }

      /**
      * Wrap the request and return interesting keys
      * @param {String} tag
      * @param {Object} req_opt
      * @param {Array} interesting_resp
      * @return {Object}
      */

      function req_wrap(tag = null, req_opt, interesting_resp = null){
      return new Promise((resolve, reject) => {
      let gen_error = gen_error_func(tag)

      if (!req_opt.url) {
      reject(gen_error(1000, 'missing url'));
      }

      let option = {
      url: req_opt.url,
      method: (req_opt.method)? req_opt.method: 'GET',
      }

      request(option, function(error, response, body) {
      if(error) {
      reject(gen_error(1001, error));
      return;
      }

      if (!response) {
      reject(gen_error(1005, 'response is undefine, maybe wrong url!'))
      return;
      }

      if (response.statusCode >= 400) {
      //http level error
      reject(gen_error(response.statusCode, body));
      }else {
      let result = {};
      let body_json;
      try {
      body_json = JSON.parse(body);
      }catch(e) {
      reject(gen_error(1002, `Unknow response: ${body}`))
      }
      if (interesting_resp) {
      interesting_resp.map(key => {
      if (body_json[key] == undefined) {
      reject(gen_error(1003, `In ${body_json}, undefined ${key}`))
      return;
      }
      result[key] = body_json[key];
      })
      }else {
      result = body_json;
      }
      resolve(result);
      }
      })
      })
      }



      • req_wrap:


        • Parameters



          • tag: Showing the request you define, ex: 'first connection'


          • req_opt: request option


          • interesting_resp: the keys what you're interesting






      NOTE: In req_wrap, if it cannot find the key in interesting_resp in response (undefined or null) the function will reject. It's necessary to check the server's spec you request!



      You can rewrite your code:



      function getPlayersInMatch(name){
      return new Promise(function(resolve, reject){
      req_wrap('first_conn', {url: api_url}, ['id']).then(result => {
      req_wrap('second_conn', {url: api_url2 + 'accountId=' + result.id}, ['participants']).then(result => {
      resolve(result.participants)
      }).catch(error => {
      reject(error)
      })
      }).catch(error => {
      reject(error)
      })
      });
      }


      Now it's more clear to check which step is wrong.






      share|improve this answer























        up vote
        0
        down vote










        up vote
        0
        down vote









        In your code, it's hard to find out which step gets error.



        I think it's better to wrap request module like:



        /**
        * Mapping knowing error_code
        * @param {Number} error_code
        * @param {String} msg
        */
        function error_def(error_code, msg) {
        let status, message;
        switch(error_code){
        case 400:
        case 401:
        case 402:
        case 403:
        case 1000:
        case 1001:
        case 1002:
        case 1003:
        case 1005:
        status = error_code;
        message = msg;
        break;
        default:
        status = 2000;
        message = 'Undefined Error'
        }
        return {status: status, msg: message};
        }

        /**
        * Generate error message
        * @param {String} tag
        * @param {Number} error_code
        * @param {String} msg
        */
        function gen_error_func(tag = null) {
        return function(error_code, msg = null) {
        return {tag: tag, error_message: error_def(error_code, msg)}
        }
        }

        /**
        * Wrap the request and return interesting keys
        * @param {String} tag
        * @param {Object} req_opt
        * @param {Array} interesting_resp
        * @return {Object}
        */

        function req_wrap(tag = null, req_opt, interesting_resp = null){
        return new Promise((resolve, reject) => {
        let gen_error = gen_error_func(tag)

        if (!req_opt.url) {
        reject(gen_error(1000, 'missing url'));
        }

        let option = {
        url: req_opt.url,
        method: (req_opt.method)? req_opt.method: 'GET',
        }

        request(option, function(error, response, body) {
        if(error) {
        reject(gen_error(1001, error));
        return;
        }

        if (!response) {
        reject(gen_error(1005, 'response is undefine, maybe wrong url!'))
        return;
        }

        if (response.statusCode >= 400) {
        //http level error
        reject(gen_error(response.statusCode, body));
        }else {
        let result = {};
        let body_json;
        try {
        body_json = JSON.parse(body);
        }catch(e) {
        reject(gen_error(1002, `Unknow response: ${body}`))
        }
        if (interesting_resp) {
        interesting_resp.map(key => {
        if (body_json[key] == undefined) {
        reject(gen_error(1003, `In ${body_json}, undefined ${key}`))
        return;
        }
        result[key] = body_json[key];
        })
        }else {
        result = body_json;
        }
        resolve(result);
        }
        })
        })
        }



        • req_wrap:


          • Parameters



            • tag: Showing the request you define, ex: 'first connection'


            • req_opt: request option


            • interesting_resp: the keys what you're interesting






        NOTE: In req_wrap, if it cannot find the key in interesting_resp in response (undefined or null) the function will reject. It's necessary to check the server's spec you request!



        You can rewrite your code:



        function getPlayersInMatch(name){
        return new Promise(function(resolve, reject){
        req_wrap('first_conn', {url: api_url}, ['id']).then(result => {
        req_wrap('second_conn', {url: api_url2 + 'accountId=' + result.id}, ['participants']).then(result => {
        resolve(result.participants)
        }).catch(error => {
        reject(error)
        })
        }).catch(error => {
        reject(error)
        })
        });
        }


        Now it's more clear to check which step is wrong.






        share|improve this answer












        In your code, it's hard to find out which step gets error.



        I think it's better to wrap request module like:



        /**
        * Mapping knowing error_code
        * @param {Number} error_code
        * @param {String} msg
        */
        function error_def(error_code, msg) {
        let status, message;
        switch(error_code){
        case 400:
        case 401:
        case 402:
        case 403:
        case 1000:
        case 1001:
        case 1002:
        case 1003:
        case 1005:
        status = error_code;
        message = msg;
        break;
        default:
        status = 2000;
        message = 'Undefined Error'
        }
        return {status: status, msg: message};
        }

        /**
        * Generate error message
        * @param {String} tag
        * @param {Number} error_code
        * @param {String} msg
        */
        function gen_error_func(tag = null) {
        return function(error_code, msg = null) {
        return {tag: tag, error_message: error_def(error_code, msg)}
        }
        }

        /**
        * Wrap the request and return interesting keys
        * @param {String} tag
        * @param {Object} req_opt
        * @param {Array} interesting_resp
        * @return {Object}
        */

        function req_wrap(tag = null, req_opt, interesting_resp = null){
        return new Promise((resolve, reject) => {
        let gen_error = gen_error_func(tag)

        if (!req_opt.url) {
        reject(gen_error(1000, 'missing url'));
        }

        let option = {
        url: req_opt.url,
        method: (req_opt.method)? req_opt.method: 'GET',
        }

        request(option, function(error, response, body) {
        if(error) {
        reject(gen_error(1001, error));
        return;
        }

        if (!response) {
        reject(gen_error(1005, 'response is undefine, maybe wrong url!'))
        return;
        }

        if (response.statusCode >= 400) {
        //http level error
        reject(gen_error(response.statusCode, body));
        }else {
        let result = {};
        let body_json;
        try {
        body_json = JSON.parse(body);
        }catch(e) {
        reject(gen_error(1002, `Unknow response: ${body}`))
        }
        if (interesting_resp) {
        interesting_resp.map(key => {
        if (body_json[key] == undefined) {
        reject(gen_error(1003, `In ${body_json}, undefined ${key}`))
        return;
        }
        result[key] = body_json[key];
        })
        }else {
        result = body_json;
        }
        resolve(result);
        }
        })
        })
        }



        • req_wrap:


          • Parameters



            • tag: Showing the request you define, ex: 'first connection'


            • req_opt: request option


            • interesting_resp: the keys what you're interesting






        NOTE: In req_wrap, if it cannot find the key in interesting_resp in response (undefined or null) the function will reject. It's necessary to check the server's spec you request!



        You can rewrite your code:



        function getPlayersInMatch(name){
        return new Promise(function(resolve, reject){
        req_wrap('first_conn', {url: api_url}, ['id']).then(result => {
        req_wrap('second_conn', {url: api_url2 + 'accountId=' + result.id}, ['participants']).then(result => {
        resolve(result.participants)
        }).catch(error => {
        reject(error)
        })
        }).catch(error => {
        reject(error)
        })
        });
        }


        Now it's more clear to check which step is wrong.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 12 at 16:39









        flyfox

        12




        12






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53245123%2fnodejs-promise-not-resolving-no-data-returned%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Florida Star v. B. J. F.

            Danny Elfman

            Lugert, Oklahoma