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?
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
})
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.