The promise get resolved in undefined [duplicate] - javascript

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

Related

JavaScript - Can't return value from function with promise [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 months ago.
I am learning promise in JavaScript but I don't understand why my function doesn't return the right value.
This is my function:
function promise() {
let p = new Promise((resolve, reject) => {
return resolve(["a", "random", "array"]);
});
p.then((response) => {
return response;
}).catch((error) => {
return error;
});
}
console.log(promise());
If I run the code I get undefined.
I think the problem is that the console.log is executed before the value of the .then is returned.
Can somebody please help me to solve this problem and maybe explain the problem? :)
Thanks for every answer.
Two things:
You must return the promise p from within the promise function.
You must await the result of the promise returned by the function before you can access its fulfilled value:
function promise() {
let p = new Promise((resolve, reject) => {
return resolve(["a", "random", "array"]);
});
p.then((response) => {
return response;
}).catch((error) => {
return error;
});
// 1. Return the promise from the function:
return p;
}
// 2. Await the result before using it:
promise().then((result) => {
console.log(result);
});
You said you're learning about promises. Async/await makes all of this much easier:
<script type="module">
// Top level await is available in ES modules
async function promise () {
try {
return ["a", "random", "array"];
}
catch (exception) {
return exception;
}
}
const result = await promise();
console.log(result);
</script>

Can't use data returned from Fetch API [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I am trying to get data from this API using fetch, and I know a promise pending is returned, but it isn't resolving itself so I can't use the data. I don't know what I am doing wrong.
function api () {
return fetch('https://api.punkapi.com/v2/beers').then(respo => { respo.json() } ).then(data => {
const beersData = data;
return beersData;
}).catch(error => {
console.error(error)
}) ;
}
api();
console.log(beersData)
First of all, you need to remove curly bracket in first then.
respo => respo.json() is equivalent to respo => { return respo.json() }.
And second, you need to handle promise when you call api function since api() also returns Promise.
function api () {
return fetch('https://api.punkapi.com/v2/beers')
.then(respo => respo.json())
.then(data => {
const beersData = data;
return beersData;
}).catch(error => {
console.error(error)
}) ;
}
api()
.then(res => {
console.log(res);
})

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

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?

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