Access result of previous promise inside a second [duplicate] - javascript

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)
}

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

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?

Returning the result from nested .then to another function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I can't work out how to return the nested .then methods, and resolve the value to the function that called it?
I can print it, at the deepest level of the last .then(), but I would like to print the returned value in the event listener.
connectedCallback () {
this.input.addEventListener('input', event => {
this.search(this.input.value)
})
}
search (str) {
let searchResult = window.fetch(`http://localhost:3000/api/?q=${str}`)
.then(result => {
return result.json()
.then(result => {
return result
})
})
}
}
Use async/await to await the promise result in the event listener. You can also simplify your promise chain considerably:
connectedCallback() {
this.input.addEventListener("input", async event => {
const result = await this.search(this.input.value);
console.log(result);
});
},
search(str) {
return window
.fetch(`http://localhost:3000/api/?q=${str}`)
.then(result => result.json());
}
I would recommend reading up on promises and getting familiar with how they work.

Get both return values of a promise chain [duplicate]

This question already has answers here:
How do I access previous promise results in a .then() chain?
(17 answers)
Closed 3 years ago.
I have a promise chain inside of a function and I would like to console.log the values returned from 2 functions inside of the chain. How would I do this? With my current code I get the value from si.cpuTemperature() then undefined but I would like to get the value from si.cpu() then si.cpuTemperature().
const si = require('systeminformation');
function getCPUInfo() {
return new Promise((resolve) => {
resolve();
console.log("Gathering CPU information...");
return si.cpu()
// .then(data => cpuInfo = data) - no need for this, the promise will resolve with "data"
.catch(err => console.log(err)); // note, doing this will mean on error, this function will return a RESOLVED (not rejected) value of `undefined`
})
.then(() => {
return si.cpuTemperature().catch(err => console.log(err));
});
}
getCPUInfo().then((data1, data2) => console.log(data1, data2));
From the docs,
systeminformation.method() returns a promise. So you don't really need to wrap it inside a promise constructor, ie new Promise()
To get the cpu and temperature, since they are not dependent on each other, you can do either use parallel promises along with an async function or just parallel promises
async function getCpuAndTemperature() {
const [cpu, temperature] = await Promise.all([
si.cpu(),
si.cpuTemperature()
])
console.log(cpu, temperature)
}
or
function getCpuAndTemperature() {
return Promise.all([
si.cpu(),
si.cpuTemperature()
])
.then(([cpu, temperature]) => {
console.log(cpu, temperature)
})
}

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)).

Categories

Resources