Reputation: 165
I am fairly new to promises and could so with any pointers on how to get this to work. None of the variations I have tried have managed to trigger the final success/error callbacks, or have managed to but haven't returned the data.
export function getData(start, end, tagSet){
let data = new dataSet();
// Initial setup to work out what data to fetch
return database.Read(config).then(function (results) {
// Process the results.......
return data;
}, function (errCode) {
// Throw Error
});
}
// Call the function, triggered by a seperate event
getData.then(function(data){
//Success !!
},function(err){
//Failure!!
});
I have also tried setting up a new promise
export function getData(start, end, tagSet){
let data = new dataSet();
// Initial setup to work out what data to fetch
return new Promise(function(resolve, reject) {
database.Read(config).then(function (results) {
// Process the results.......
// Update data
}, function (errCode) {
// Throw Error
});
return data;
}
}
I don't want to make the getData function blocking by using await, so what is the correct way to return data from a promise inside a function?
Upvotes: 0
Views: 157
Reputation: 165
Looks like the solution I wanted was to set the function as async and use an await.
export async function getData(start, end, tagSet){
let data = new dataSet();
// Initial setup to work out what data to fetch
await database.Read(config).then(function (results) {
// Process the results.......
// update data
}, function (errCode) {
// Throw Error
});
return data;
}
// Call the function, triggered by a seperate event
getData().then(function(data){
// Success !!
// data has been completed here
},function(err){
// Failure!!
});
This results in the returned data being completed before being the getData().then() is triggered.
Upvotes: 0
Reputation: 164
You don't return anything from promises, but instead resolve or reject a promise.
your 2nd example should look something like this
export function getData(start, end, tagSet){
let data = new dataSet();
// Initial setup to work out what data to fetch
return new Promise(function(resolve, reject) {
database.Read(config).then(function (results) {
// Process the results.......
// Update data
}, function (errCode) {
// Throw Error
reject(errCode) // <-- if error happens, you reject your promise with error
});
resolve(data) // <<-- if there is no error, you resolve your data
}
}
then you can use
getData.then(function(data){
//promise is resolved
})
.catch(function(err){
//promise was rejected
})
Upvotes: 1