I am trying to write a piece of code using promises, avoiding nesting them but I am stuck in testing the returned results to handle the promises flow ..
Is this pattern workable ??
// set of promise tasks returning values
function doTask1() => {
return apiPromise1()
.then((result1) => {
return result1;
})
}
function doTask2(result1, paramOne) => {
return apiPromise2(result1, paramOne)
.then((result2) => {
return result2;
})
}
function doTask3(result1) => {
return apiPromise3()
.then((result3) => {
return result3;
})
}
function doTask4(result1, paramOne) => {
return apiPromise4()
.then((result4) => {
return result4;
})
}
// main promise to handle the flow of promises according to promises returned results
function getCurrentProcess(paramOne) {
const promises = [];
// how to get the returned result1 to be used by other promises ?
promises.push(doTask1);
if (result1 === 'OK') {
promises.push(doTask2(result1, paramOne));
if (result2 === 'OK') {
promises.push(doTask3(result1));
if (result3 === 'OK') {
promises.push(doTask4(result1, paramOne));
}
}
}
return Promisz.all(promises)
.then(() => {
return 'well done'
});
}
// initial calling function
exports.newJob = functions.https.onRequest((req, res) => {
const paramOne = { ... }
getCurrentProcess(paramOne).then((res) => {
return { status: 200, infos: res };
}, error => {
return {status: error.status, infos: error.message};
}).then(response => {
return res.send(response);
}).catch(console.error);
});
If you want to write promises in more procedural way you need use async/await (ES6). If you need backward compatibility with ES5 you need to use babel or typescript which translate await/async to ES5.
async function getCurrentProcess(paramOne) {
const result1 = await doTask1();
if (result1 === 'OK') {
const result2 = await doTask2(result1, paramOne);
if (result2 === 'OK') {
const result3 = await doTask3(result1);
if (result3 === 'OK') {
await doTask4(result1, paramOne);
}
}
}
return 'well done'
}
Without async/await you need to use promise chain:
doTask1().then((result1)=>{
if (result1 === 'OK') {
...
}
...
})
However it will not produce readable code.
You could write a wrapper function which takes an array of doTaskN as deferred functions:
const conditional = (...fns) => {
if(fns.length === 0) return Promise.resolve();
const [next] = fns;
return next()
.then(() => conditional(...fns.slice(1)));
};
The idea would be to pass in the reference to the doTask functions so that the conditional function executes them. This can be used like:
conditional(doTask1, doTask2, doTask3, doTask4)
.then(() => {
console.log("all done");
})
.catch(() => {
console.log("failed");
});
Here's a full example of how to use it:
const conditional = (...fns) => {
if(fns.length === 0) return Promise.resolve();
const [next] = fns;
return next()
.then(result => {
console.log("task:", result);
if(result === "OK") {
return conditional(...fns.slice(1))
}
});
};
const task1 = (param1, param2) => Promise.resolve("OK");
const task2 = (param1) => Promise.resolve("OK");
const task3 = () => Promise.resolve("failed");
const task4 = () => Promise.resolve("OK");
conditional(() => task1("one", 2), () => task2(1), task3, task4)
.then(() => {
console.log("all done");
})
.catch(() => {
console.log("failed");
});
If you want that your promise return result is used by other promises, you shouldn't use Promise.all() method because it doesn't run methods in the order you want, it just waits for all of the promise methods to complete and returns all results.
Maybe something like promise-array-runner would help?
Maybe you could check if result === 'OK' inside your task method? Or create a Factory which takes care of that.
.then((result1) => {
return result1;
})
is a no-op and should be omitted, but I suppose that real code doesn't have this problem.
This is a use case for async function because they can seamlessly handle this sort of control flow, as another answer suggests. But since async is syntactic sugar for raw promises, it can be written in ES6. Since tasks depend on results of each other, they cannot be processed with Promise.all.
This is same case as this one that uses async.
You can bail out from promise chain by throwing an exception and avoid nested conditions with:
// should be additionally handled if the code is transpiled to ES5
class NoResultError extends Error {}
function getCurrentProcess(paramOne) {
doTask1()
.then(result1 => {
if (result1 !== 'OK') throw new NoResultError(1);
return result1;
})
.then(result1 => ({ result1, result2: doTask2(result1, paramOne) }))
.then(({ result1, result2 }) => {
if (result2 !== 'OK') throw new NoResultError(2);
return result1;
})
// etc
.then(() => {
return 'well done';
})
.catch(err => {
if (err instanceof NoResultError) return 'no result';
throw err;
})
}
Since result1 is used in multiple then callbacks, it could be saved to a variable instead of being passed through promise chain.
Promise chain could become simpler if NoResultErrors were thrown in task functions.
Thanks to all feedbacks !!
All answers are rights... however I voted for CodingIntrigue wtapprer function solution in my case...
1 - As i am using Firebase functions , it's still ES5 , I cannot use sync/await. Using babel or typescript only for Firebase functions will result in much more setup work...
2 - I tested various use cases and this pattern is quite easy to understand with JS level... I am sur that it can be improved later..
so finally I got this running ...
let auth = null;
let myList = null;
const conditional = (...fns) => {
if(fns.length === 0) return Promise.resolve();
const [next] = fns;
return next()
.then(result => {
if(result) {
return conditional(...fns.slice(1));
}
return result;
});
};
const task1 = (param1) => Promise.resolve()
.then(() => {
console.log('TASK1 executed with params: ', param1)
auth = "authObject"
return true;
});
const task2 = (param1, param2) => Promise.resolve()
.then(() => {
console.log('TASK2 executed with params: ', param1, param2)
return true;
});
const task3 = (param1, param2) => Promise.resolve()
.then(() => {
console.log('TASK3 executed with params: ', param1, param2)
myList = "myListObject"
console.log('search for param2 in myList...')
console.log('param2 is NOT in myList task4 will not be executed')
return false;
});
const task4 = (param1) => Promise.resolve()
.then(() => {
console.log('TASK4 executed with params: ', param1)
return true;
});
// FIREBASE HTTP FUNCTIONS ==================
exports.newContactMessage = functions.https.onRequest((req, res) => {
conditional(() => task1("senderObject"), () => task2(auth, "senderObject"), () => task3(auth, "senderObject"), () => task4("senderObject"))
.then((res) => {
return { status: 200, infos: res };
}, error => {
return {status: error.status, infos: error.message};
}).then(response => {
return res.send(response);
}).catch(console.error);
});
Related
any idea why my cloud function is telling my that (Not all code paths return a value) I put a return on the promise at the end also on the if statement yet it is not working, I read about similar issues tried to solve according to them but I still missing part of the puzzle, the error started showing when I wrapped the whole thing with try-catch.
export const createClient = functions.https.onCall(async(data, context) => {
try {
const snapshotCheckBelong = await db.collection('data- main').doc(data.sharedId).get();
const getClient = snapshotCheckBelong.data() ? .clients.filter((el: any) => el.clientId === data.clientId);
const snapshotCheckExist = await db.collection('data-registered-clients').doc(data.sharedId).get();
const checkClient = snapshotCheckExist.data() ? .clients.filter((el: any) => el.clientId === data.clientId);
if (checkClient[0]) {
return {
result: 'Registered client already exisits.'
};
}
if (getClient[0] ? .clientId === data.clientId && checkClient.length === 0) {
const payload = {
user: 'client',
verifiedEmail: false,
createdAt: admin.firestore.Timestamp.now(),
};
let auth = admin
.auth()
.getUserByEmail(context.auth ? .token ? .email!)
.then((user) =>
admin.auth().setCustomUserClaims(user.uid, {
userType: 'client',
premiumUnitll: admin.firestore.Timestamp.fromDate(snapshotCheckBelong.data() ? .premiumUntill)
})
)
.catch((err: any) => {
console.log(err);
});
let setClientData = db
.collection('data-clients')
.doc(context.auth ? .uid!)
.set(payload)
.catch((err: any) => {
console.log(err);
});
let updateRegisteredClients = db
.collection('data-registered-clients')
.doc(data.sharedId)
.update({
clients: admin.firestore.FieldValue.arrayUnion({
clientAccount: context.auth ? .uid,
clientId: data.clientId,
trainerId: data.sharedId
})
})
.catch((err: any) => {
console.log(err);
});
return Promise.all([auth, setClientData, updateRegisteredClients]);
} else {
return null;
}
} catch {
(err: any) => {
console.log(err);
};
}
});
Your catch blocks are not returning anything. If you handle an error with catch, you have to determine what value gets returned to the caller.
I typically prefer sending the error back to the caller, as shown in the documentation on handling errors in callable cloud functions and on the calling client.
I am fetching some exchange data from DB, then extracting the name of distinct exchanges and passing again into MYSQL query to fetch data from a different table.
The problem I am facing is that async await does not return the value rather just return Promise { }.
Below is the code that I am trying, wondering where I am going wrong.
//Function that fetches the exchanges from DB
const getExchange = () => {
return new Promise((resolve, reject) => {
db.connection.query(`
SELECT *
FROM,
(
SELECT
exchange,
COUNT(pair) as noOfMarkets
FROM ticker_data
) as t
`, (err, resp) => {
if (!err) {
resolve(resp)
} else {
reject(err)
}
})
})
}
// push unique exchanges to an array.
const getExchangesData = async () => {
const allExchanges = await getExchanges();
let exchanges = []
allExchanges.forEach(item => {
let exchange = {
exchange: item.exchange
}
exchanges.push(exchange)
})
return await exchanges
}
// mapping through an array of exchanges and passing to DB query to get data from the DB.
const getSingleExchange = async () => {
const exchanges = await getExchangesData()
await Promise.all(exchanges.map(async (item) => {
db.connection.query(`
SELECT
exchange_rank,
name
volume24hUSD
(
SELECT
volume24hUSD as tradingVolYesterday
FROM exchanges
WHERE name = '${item.exchange}'
AND createdAt >= now() -interval 1 day
AND createdAt < now() -interval 1 day + interval 120 second
LIMIT 1
) volumeDay1
FROM exchanges
WHERE name = '${item.exchange}'
`, (err, resp) => {
if (!err) {
console.log(resp) // getting all the values
let volData = {
name: resp[0].name,
exchange_rank: resp[0].exchange_rank,
icon: resp[0].icon
}
return volData
}
})
}))
}
const data = getSingleExchange()
console.log(data) // returning Promise { <pending> }
Edit
After making changes suggested in an answer, I still have an issue:
//Function that fetches the exchanges from DB
const getExchange = () => {
return new Promise((resolve, reject) => {
db.connection.query(`
SELECT *
FROM,
(
SELECT
exchange,
COUNT(pair) as noOfMarkets
FROM ticker_data
) as t
`, (err, resp) => {
if (!err) {
resolve(resp)
} else {
reject(err)
}
})
})
}
// push unique exchanges to an array.
const getExchangesData = async () => {
const allExchanges = await getExchanges();
let exchanges = []
allExchanges.forEach(item => {
let exchange = {
exchange: item.exchange
}
exchanges.push(exchange)
})
return await exchanges
}
// mapping through an array of exchanges and passing to DB query to get data from the DB.
const getSingleExchange = async () => {
const exchanges = await getExchangesData()
await Promise.all(exchanges.map((item) => {
return new Promise((resolve, reject) => {
db.connection.query(`...`, (err, resp) => {
if (!err) {
resolve(resp)
} else {
reject(err)
}
}).then(resp => {
console.log(resp)
let volData = {
name: resp[0].name,
exchange_rank: resp[0].exchange_rank,
icon: resp[0].icon
}
return volData
})
})
}))
}
getSingleExchange().then(data => {
console.log(data)
});
I now get this error:
(node:30583) UnhandledPromiseRejectionWarning: TypeError: db.connection.query(...).then is not a function
at Promise (/getExchanges.js:217:16)
at new Promise ()
at Promise.all.exchanges.map (/getExchanges.js:145:16)
at Array.map ()
at getSingleExchange (/getExchanges.js:144:33)
The main issue is in this part:
await Promise.all(exchanges.map(async (item) => {
That map callback is not returning anything, and it has no await, so using async makes no sense.
Instead remove async:
await Promise.all(exchanges.map((item) => {
... and return a promise in the callback function, much like you had done in the first function:
return new Promise((resolve, reject) => {
db.connection.query(`...`), (err, resp) => {
if (!err) {
resolve(resp)
} else {
reject(err)
}
})
}).then(resp => {
console.log(resp)
let volData = {
name: resp[0].name,
exchange_rank: resp[0].exchange_rank,
icon: resp[0].icon
}
return volData
});
You would benefit from writing one generic function that promisifies query, so that you don't have to do that new Promise-thing for every single query you need.
Finally, you cannot expect to get an asynchronous result synchronously: async functions do not return the asynchronous result synchronously, but return a promise for it. So your last lines (main code) should still await. So either do this:
(async () => {
const data = await getSingleExchange()
console.log(data)
})(); // immediately executing (async) function expression
Or:
getSingleExchange().then(data => {
console.log(data)
});
NB: doing return await exchanges in the second function makes no sense (exchanges is not a promise), so you can just do return exchanges.
I know when we use promise in JavaScript, we usally use two ways like below.
var f1 = () => {
return new Promise( (resolve, reject) => {
resolve(10);
})
}
var f2 = () => {
return Promise.resolve(10)
}
f1().then( data => { console.log(data) }) // 10
f2().then( data => { console.log(data) }) // 10
But if i use async function inside of promise, Promise.resolve lost the value like below.
const fs = require('fs')
var f1 = () => {
return new Promise( (resolve, reject) => {
fs.readFile('data.txt', (err, data) => {
resolve(data);
})
})
}
var f2 = () => {
return Promise.resolve()
.then(() => {
fs.readFile('data.txt', (err, data) => {
//return data --> undefined
//Promise.resolve(data) --> undefined
return Promise.resolve() --> undefined
})
})
}
f1().then( data => { console.log('1,',data) })
f2().then( data => { console.log('2,',data) })
I think that i use wrong way about Promise.resolve,,, OR Promise.resolve not support async function... someone tell me why Promose.resolve fail..
If you have a value that you immediately want to resolve a promise with, you can use Promise.resolve().
If you get the value asynchronously in a callback, you must use the new Promise constructor with the resolve/reject callbacks, there is no way around it.
I'm attempting to query an API which responds with a ReadableStream of XML.
The code below uses a recursive Promise. Recursive because it sometimes doesn't decode the stream in a singular iteration and this is whats causing my headache.
While I'm successfully fetching the data, for some reason the decoding stage doesn't complete sometimes, which leads me to believe it's when the stream is too large for a single iteration.
componentDidMount() {
fetch("http://thecatapi.com/api/images/get?format=xml&size=med&results_per_page=9")
.then((response) => {
console.log('fetch complete');
this.untangleCats(response);
})
.catch(error => {
this.state.somethingWrong = true;
console.error(error);
});
}
untangleCats({body}) {
let reader = body.getReader(),
string = "",
read;
reader.read().then(read = (result) => {
if(result.done) {
console.log('untangling complete'); // Sometimes not reaching here
this.herdingCats(string);
return;
}
string += new TextDecoder("utf-8").decode(result.value);
}).then(reader.read().then(read));
}
I think that the next iteration was sometimes being called before the current iteration had completed, leading to incorrectly concatenation of the decoded XML.
I converted the function from sync to async and as a regular recursive method of the component rather than a recursive promise with a method.
constructor({mode}) {
super();
this.state = {
mode,
string: "",
cats: [],
somethingWrong: false
};
}
componentDidMount() {
fetch("http://thecatapi.com/api/images/get?format=xml&size=med&results_per_page=9")
.then( response => this.untangleCats( response.body.getReader() ) )
.catch(error => {
this.setState({somethingWrong: true});
console.error(error);
});
}
async untangleCats(reader) {
const {value, done} = await reader.read();
if (done) {
this.herdingCats();
return;
}
this.setState({
string: this.state.string += new TextDecoder("utf-8").decode(value)
});
return this.untangleCats(reader);
}
I've a promise in Parent class, whenever I call the promise from child class, it is returning the undefined, instead of executing the promise and returning the resul.
import {newsApiKey as APIKEY, newUrl as APIURL} from "./secretToken";
class News{
constructor(){
this.token = APIKEY;
this.url = APIURL;
this.source = 'bbc-news&';
}
topNews(){
const bbcNews = fetch(`${this.url}?source=${this.source}&sortBy=top&apiKey=${this.token}`);
bbcNews.then(response => {
if (!response.ok) {
throw Error(response.statusText);
}
return response.json()
})
.then(json => {
console.log(json.articles);
return json.articles;
})
.catch((err) => {
return err.message;
});
}
}
export { News as default};
CHILD CLASS
import News from "./news";
class StickyNote extends News{
displayNews(){
let bbcNews = super.topNews(); // It is returning only undefined
if (typeof bbcNews != 'undefined') {
console.log(bbcNews); //
}
}
}
topNews never returns anything, so the result of calling it is undefined.
You probably wanted a return here:
topNews() {
const bbcNews = fetch(`${this.url}?source=${this.source}&sortBy=top&apiKey=${this.token}`);
return bbcNews.then(response => {
// ^^^^^^
if (!response.ok) {
throw Error(response.statusText);
}
return response.json()
})
.then(json => {
console.log(json.articles);
return json.articles;
})
.catch((err) => {
return err.message;
});
}
Also note that displayNews will need to use the promise it receives:
displayNews(){
super.topNews().then(articles => {
// ...use articles
});
}
(Normally you'd also have a catch there at the endpoint of consumption, but as you've converted rejections into resolutions...)
Note: That code has a bit of an anti-pattern in it: It converts a rejection into a resolution with an error message. Anything using the promise will never see a rejection, only resolutions with varying return types (whatever json.articles is or a string). In general, it's better to allow rejections to propagate, and handle them at the ultimate point of consumption of the entire chain (displayNews, I believe, in your example). You might transform their content, but not convert them from a rejection into a resolution.
FWIW, I'd probably rewrite that like so:
topNews() {
return fetch(`${this.url}?source=${this.source}&sortBy=top&apiKey=${this.token}`)
.catch(_ => {
throw new Error("network error");
})
.then(response => {
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json();
})
.then(data => { // "data", not "json" -- it's not JSON anymore
return data.articles;
});
}
...which ensures that the caller either gets a resolution with the articles, or a rejection with an Error, so:
displayNews(){
super.topNews()
.then(articles => {
// ...use articles
})
.catch(err => {
// ...show error
});
}