A
A
asd dsa2019-12-23 23:43:16
JavaScript
asd dsa, 2019-12-23 23:43:16

How to use a promise value for a condition?

I want to implement lazy loading of a component and use its method mockedClient for a condition. which I pass from the command line.
Lazy loading component:

const mockedClient = () => createMockedClient({
    mocks,
    typeDefs,
})

export {
    mockedClient
}

A place where, provided I want to use a method from a component to include or not include a component in a bundle
const getMockedClient = () => import("z-mock-client")
const mocked = getMockedClient ().then(prop => prop.mockedClient()) // initialize ApolloClient 
const apolloProvider = new VueApollo({
    defaultClient: MOCKED_UI ? mocked : v2,
    clients: {
        v2: MOCKED_UI ? mocked : v2
    }
})

But instead of the value in the variable, mockedI get this :
Promise {<pending>}
: "resolved"
: ApolloClient

How can I make it so that the value of is initialized in the mocked variable?
Then I can insert it in the condition where apolloClient is replaced by apolloProvider and thus I will add or not the "z-mock-client" component to the js bundle.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2019-12-24
@yaNastia

Promise value can be obtained either via await or inside then, you can't get it directly as it is executed asynchronously and at the time of assignment
const mocked = getMockedClient ().then(prop => prop.mockedClient())
it has not yet executed , it's just a declaration of intent.
That is, either
then the code will wait for the promise to be executed, before the name of the function inside which await is used, you need to put async
or

getMockedClient ().then(prop => {
  const mocked = getMockedClient ()
  // И тут делаете с полученным значением что хотите
})

In general, just read any article about promises on the internet, there are a lot of them

E
Evgeny Kulakov, 2019-12-24
@kulakoff Vue.js

Well, it’s like a promise is returned to you and it will resolve sometime later than your piece of code.
Why not just something like this:

const mocked = require("z-mock-client")()
const apolloProvider = new VueApollo({
    defaultClient: MOCKED_UI ? mocked : v2,
    clients: {
        v2: MOCKED_UI ? mocked : v2
    }
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question