Why my this return Promise { <pending> }? [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my asynchronous function returning Promise { <pending> } instead of a value?
(9 answers)
Closed 2 years ago.
I don't understand a lot about Promises.
I have this function to read data in JSON file:
const getData = (fileName) =>
new Promise((resolve, reject) =>
fs.readFile(fileName, 'utf8', (err, data) => {
console.log("Tipo da data:", typeof(data))
return err ? reject(err) : resolve(data);
})
);
I do this:
const hashList = getData('./users/hashList.json')
.then(data => console.log(data))
.catch(error => console.log('Error: ', error));
'./users/hashList.json' is something like that ["2d37c88b9e650846b5eb0d2c0f38ecbf8601f6c5"]
I want to know if the hashReceived is in this hashList, I do this:
if(hashList.includes(receivedHash)){
console.log("ok")
}
But when I run the code, I have this error: TypeError: hashList.includes is not a function.
When I console hashList, I receive this: Promise { }
Someone would help me to resolve that as assynchronous function? I only resolve using readSync, is readSync the only way to resolve that?

Related

The promise get resolved in undefined [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I'm trying to understand how promises and the async-await stuff work and I built the following code to get the list of connected devices on the computer but it returns 'undefined'.
var iosDevice = require("node-ios-device");
const the_action = () => {
iosDevice.devices(function (err, devices) {
if (err) {
console.error("Error!", err);
} else {
return devices;
}
});
}
const create_promise = () => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(the_action()), 100);
});
};
const the_devices = create_promise();
const resolvePromise = (promise) => {
promise
.then((result) => console.log(result))
.catch((error) => HTMLFormControlsCollection.log(error));
};
resolvePromise(the_devices);
I'm running the above script from terminal using node:
$> node the_script.js
What am I'm doing wrong or missing?
Thank you in advance
the_action isn't returning anything. Your return statement simply returns from the iosDevice.devices callback - but the containing function doesn't return anything. That's where your problem lies. If you get the_action to return something, it will bubble up through your promise resolution and end up getting console.logged

promise is still pending in then block - how to resolve? [duplicate]

This question already has answers here:
Why is my asynchronous function returning Promise { <pending> } instead of a value?
(9 answers)
Closed 4 years ago.
I have code something like -
fetch(`${URL}${PATH}`)
.then(res => {
const d = res.json();
console.log("data is: ", d);
return d;
})
It logs data is: Promise { <pending> }.
What to do to see results and utilize in next code statement?
Other questions and answers suggests to use then block to resolve, but I'm still seeing it unresolved.
res.json() is asynchronous. You will need to use an additional .then to get the result.
fetch(`${URL}${PATH}`)
.then(res => res.json())
.then(d => {
console.log('data is: ', d);
return d;
});
Well If you are getting this type of value Promise { <pending> }. Always remember to resolve it.
So your query would resolve to
fetch(`${URL}${PATH}`)
.then(res => res.json())
.then(console.log)
.catch(console.error)
For better understanding you can leverage the use of async/await feature. The above code would reduce to-
try{
const res = await fetch(`${URL}${PATH}`)
const dataAsJson = await res.json()
console.log(data)
}
catch(ex) {
console.error(ex)
}

Access result of previous promise inside a second [duplicate]

This question already has answers here:
How do I access previous promise results in a .then() chain?
(17 answers)
Closed 4 years ago.
I'm using the return pattern to prevent me from making promise ugly cascade.
Here is an exemple, I'm calling two function one after the other myfunction1 and myfunction2
myfunction1().then((value1) => {
return myfunction2()
}).then((value2) => {
console.log(value1)
}).catch((err) => {
console.error(err)
})
How can I access value1 inside the then of the seconde function ?
You must pass it through your chain. That's why I started using async/await:
try {
var value1 = await myfunction1();
var value2 = await myFunction2();
console.log(value1)
} catch (err) {
console.error(err)
}
you have to "chain" your promises like this:
myfunction1().then((value1) => {
return myfunction2().then((value2) => {
console.log(value1)
})
}).catch((err) => {
console.error(err)
}

Unhandled Promise Rejection with a .catch() [duplicate]

This question already has answers here:
why settimeout not delay the function execution?
(2 answers)
Closed 5 years ago.
I'm having trouble debugging my first Javascript tool which uses promises. I feel like I am using the .catch() method correctly, as it matches up with other StackOverflow answers to similar questions that have been asked, however I'd still receiving an UnhandledPromiseRejectionWarning for uncaught promises.
My program fetches a list of objects from an S3 and then logs them to console.
Here is the promise chain
s3Helper.setCredentials(program.profile)
.then(s3Helper.findObjects([], null))
.then(data => console.log(data))
.catch(err => utl.error(err));
And here are the two promises
function findObjects (keyArray, token) {
return new Promise((resolve, reject) => {
var S3 = new AWS.S3({apiVersion: '2006-03-01'});
var params = {
Bucket: program.bucket,
Prefix: program.prefix,
Delimiter: program.recursive ? '' : '/',
ContinuationToken: token
};
S3.listObjectsV2(params, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
}
function setCredentials (profile) {
// Sets AWS credentials, and rejects if the profile is not found
return new Promise((resolve, reject) => {
AWS.config.credentials = new AWS.SharedIniFileCredentials({profile: profile});
AWS.config.credentials.refresh((err, data) => {
if (err) {
reject(err);
} else if (AWS.config.credentials.accessKeyId) {
resolve();
} else if (AWS.config.credentials.roleArn) {
resolve();
} else {
var error = {
message: `Given profile '${program.profile}' does not exist`
};
reject(error);
}
});
});
}
Sorry if my style or code is bad, I'm still getting used to Javascript!
Your promise chain should look like this:
s3Helper.setCredentials(program.profile)
.then(() => s3Helper.findObjects([], null))
.then(data => console.log(data))
.catch(err => util.error(err));
Note the function: () => ... on the second line
Then .then() method takes a function as it's argument. So you must pass it a function.
Therefore, .then(s3Helper.findObjects([], null)) would only work if s3Helper.findObjects([], null) returns a function. But based on you definition of s3Helper.findObjects([], null), it doesn't. So you need to update your .then() method to .then(() => s3Helper.findObjects([], null)).

returning promise to a variable without $$state [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have the following promise
let oembedData = oembed(uuid)
.then(res => res);
console.log(oembedData);
What I'm hoping to achieve is to return the res to oembedData so the value can be used.
I know I can do
let oembedData;
oembed(uuid)
.then((res) => {
oembedData = res;
console.log(oembedData);
});
but I feel this way isn't as clean as the former example.
When I use the former my console log returns Promise {$$state: {…}}
If you're free to use async/await, it looks almost like you'd want.
async function oembed(uuid) {
return new Promise(resolve => setTimeout(() => {
resolve('foo');
}, 3000));
}
async function getOembed() {
try {
const oembedData = await oembed('1234');
console.log(oembedData);
} catch(err) {
handleError(err);
}
}
getOembed();

Categories

Resources