How do I wait for a promise to finish before returning the variable of a function?

前端 未结 4 492
情话喂你
情话喂你 2020-11-29 23:15

I\'m still struggling with promises, but making some progress thanks to the community here.

I have a simple JS function which queries a Parse database. It\'s suppose

4条回答
  •  隐瞒了意图╮
    2020-11-30 00:02

    What do I need to do to make this function wait for the result of the promise?

    Use async/await (NOT Part of ECMA6, but available for Chrome, Edge, Firefox and Safari since end of 2017, see canIuse)
    MDN

        async function waitForPromise() {
            // let result = await any Promise, like:
            let result = await Promise.resolve('this is a sample promise');
        }
    

    Added due to comment: An async function always returns a Promise, and in TypeScript it would look like:

        async function waitForPromise(): Promise {
            // let result = await any Promise, like:
            let result = await Promise.resolve('this is a sample promise');
        }
    

提交回复
热议问题