Tell me please. How to do it correctly so that until the block of code number 1 is executed, action number 2 was not performed

enter image description here

export const getAllQues = (collection) => { return async (dispatch) => { const db = firebase.firestore(); const settings = { timestampsInSnapshots: true }; db.settings(settings); const allquestions = {}; const docRef = db.collection(collection); try { const doc = await docRef.get(); doc.forEach(async (item) => { const array = []; const ref = db.collection(collection).doc(item.id).collection('questions'); const total = await ref.get(); total.forEach(async (interval) => { array.push(interval.data()); }); allquestions[item.id] = array; }); } catch (e) { throw e; } const result = allquestions; dispatch(allQues(result)); return result; }; }; 

  • Is the question still relevant? - Pavel Mayorov

2 answers 2

 Promise.all(doc.map(item => new Promise(async (resolve, reject) => { const ref = db.collection(collection).doc(item.id).collection('questions'); const total = await ref.get(); allquestions[item.id] = total.map(interval => interval.data()); resolve(); }))); 
  • Well, what for to create a new Promise around an asynchronous function? - Pavel Mayorov
  • @Pavel Mayorov well, so how else to perform my task? - sinevitch
  • @sinevitch is easier - Pavel Mayorov
  • Tell me if it's not difficult? - sinevitch

Below is the code that solves your problem. In it, I used the bluebird library, which provides advanced functionality for working with promises. The code block number 1 was moved to a separate asynchronous function that will be called with await and will allow you to execute code block 2 only after the execution of this function.

 const Promise = require('bluebird'); export const getAllQues = (collection) => { return async (dispatch) => { const db = firebase.firestore(); const settings = { timestampsInSnapshots: true }; db.settings(settings); const docRef = db.collection(collection); const allquestions = await getAllQuestions(docRef, db); dispatch(allQues(allquestions)); return allquestions; }; }; async function getAllQuestions(docRef, db) { try { const doc = await docRef.get(); const allquestions = {}; await Promise.each(items, async (item) => { const ref = db.collection(collection).doc(item.id).collection('questions'); const total = await ref.get(); const intervals = await Promise.map(total, (interval) => interval.data()); allquestions[item.id] = intervals; }); return allquestions; } catch (e) { throw e; } } 
  • Please try to leave more detailed answers. What is this piece of code? - 0xdb