Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
98
rated 0 times [  101] [ 3]  / answers: 1 / hits: 47407  / 7 Years ago, thu, august 10, 2017, 12:00:00

I'm having a bit of an issue with an error dealing with promises.
So initially I had my function set up like this, and it all worked fine, no problems.



Original:



const request = require(request-promise);
async () => {
const URL_HIDDEN = ...;

let info = await request(URL_HIDDEN);
info = JSON.parse(info).response.players[0];

let playtime = await request(URL_HIDDEN);
playtime = JSON.parse(playtime).response.games;

console.log(info);
console.log(playtime);
}


This is a shortened version, but basically I am just requesting information from the Steam API. Both the variables get print out with all the data no problem, but that changes once I do the refactor below.



Refactored:



const middleware = require(../middleware);
async () => {
const URL_HIDDEN = ...;

let requests = middleware.requestURI(URL_HIDDEN);
console.log(requests);
}


and I started doing all the request handling in a separate function in a separate file.



const request = require(request-promise);
middlewareObj.requestURI = async (URL_HIDDEN) => {
console.log(1);
let info = await request(URL_HIDDEN);
info = JSON.parse(info).response.players[0];

console.log(2);

let playtime = await request(URL_HIDDEN);
playtime = JSON.parse(playtime).response.games;

console.log(3);

return [{ info }, { playtime }];
};


Once I got all the variables sorted out I want to return an array. However, once executed I get this printed to the console.



1
Promise { <pending> }
2
3


Any idea why it's printing promise pending once I refactored it?



In the original it prints out everything perfectly fine


More From » node.js

 Answers
5

in your Refactored code -



let requests = middleware.requestURI(URL_HIDDEN);


without an await, requests will be a pending promise - so, you need



let requests = await middleware.requestURI(URL_HIDDEN);


To expand on this. Any function tagged async will return a Promise.



async function foo() {
return true;
}


calling this like



let bar = foo();
// here bar = pending promise of foo()


Results in bar being the Promise



calling it like



let bar = await foo(); 
// here bar == true


is sort of equivalent (but nowhere near equal) to



foo().then(bar => {
// here bar == true
})


async/await can make code that is already simplified by Promise's even simpler - in this contrived example, it's not obvious though


[#56810] Tuesday, August 8, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dawnc

Total Points: 612
Total Questions: 94
Total Answers: 98

Location: Sweden
Member since Fri, Apr 16, 2021
3 Years ago
dawnc questions
Fri, Nov 26, 21, 00:00, 3 Years ago
Wed, Jul 15, 20, 00:00, 4 Years ago
Sun, Dec 15, 19, 00:00, 5 Years ago
Thu, May 30, 19, 00:00, 5 Years ago
;