P
P
partyzanx2020-02-25 03:46:04
JavaScript
partyzanx, 2020-02-25 03:46:04

How to wait for an async function inside an async function?

import translate from 'translate';  
...
export const search = async (req, res) => { 

...

const makeDictionaryTree = async elem => {
    let newArr = []
    for (let e of elem) { 
        let obj = new Object();
        obj.pinyin = e.pinyin;
        obj.definitions = e.definitions;
        for (let e of obj.definitions) {
            console.dir(e, ' = ')
            e = await translate(e, { to: 'ru', engine: 'google', key: process.env.TRANSLATE_KEY })
            console.dir(e)
        }
        newArr.push(obj)
    }
    return newArr
 }

...

    words = newArr.map(e => {
                            let newE = new Object();
                            newE.character = e; 
                            newE.decomp = decomp.lookup(e); 
                            newE.decomp2 = hanzi.decompose(e, 1);
                            newE.decomp3 = hanzi.decompose(e, 2);
                            newE.entries = makeDictionaryTree(getEntries(e));
                            return newE; 
                        })
 
...

    console.log(words)
    res.render("search", { pageTitle: "Search", searchingBy, newUrl, uniqueCharSet, words: words })
};


console.log(words[0].entries) Outputs Promise { }
It turns out that the script does not wait for the makeDictionaryTree function and immediately renders the page

[
  {
    character: '觉',
    decomp: { label: '觉', children: [Array] },
    decomp2: { character: '觉', components: [Array] },
    decomp3: { character: '觉', components: [Array] },
    entries: Promise { <pending> }
  }
]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Robur, 2020-02-25
@partyzanx

words = await Promise.all(newArr.map( async e => {
                            let newE = new Object(); 
                            newE.entries = await makeDictionaryTree(getEntries(e));
                            return newE; 
                        }))

well, or instead of newArr.map for, make it so that they are called in turn and not in parallel

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question