How to change js Asynchronous method to Synchronize method

export const getUserToken = () => {
  let result = "";
  
  setupWebViewJavascriptBridge((bridge) => {
    bridge.callHandler("fetchUserInfo", (data) => {
      // 
      result = data;
    });
  });

  return result;
};

this is an interactive method between h5 and iOS, that is, an iOS method is called, iOS returns a parameter, and iOS is returned in a callback method. Calling this method returns the default empty string before it can be copied to result. Ask the gods to guide you how to write to return the normal results?

Apr.01,2021

Changing

to Synchronize is hard to implement. JS itself is an asynchronous event stream feature.
feel free to use callbacks. If your environment supports it, you can choose to use async / await to make the code look like Synchronize:

.

resultasync/await

1.

export const getUserToken = (cb) => {
  setupWebViewJavascriptBridge((bridge) => {
    bridge.callHandler('fetchUserInfo', (data) => {
      // 
      cb && cb(data)
    });
  });
};

//

getUserToken(fucntion(data){
    console.log(data)
    //dada
})

2. async/await Mode

export const getUserToken = () => new Promise((resolve, reject) => {
  setupWebViewJavascriptBridge((bridge) => {
    bridge.callHandler('fetchUserInfo', (data) => {
      resolve(data)
    })
  })
})

// :

async function(){ //`await``data `
    const data = await getUserToken()
    console.log(data )
}
Menu