简体   繁体   中英

Dynamic js bundle synchronous api call

My case is I have a js web app that I bundle with webpack. The app is deployed to a azure webapp where I like to make use of the Application Settings feature. Particular I like to be able to set the api base url the app should use. To make that work my idea is to place a .php in the root which simple return something like {url: 'api.mypage.com'} . The .php can read the evironment variable and return correct url based on the environment. Today when I bundle my js it reads the .config with the api url which makes the bundle environment dependent. I have been trying to make a call relative to it self (/api.php) that works fine. The problem is a can't get it working synchronously.

How would you guys solve this? I'm not a js expert but there must be a smart solution fot this. I have been fibbleing with somthing like this:

const dynConfig = {
    apiUrl: getApiBaseUrl((param) => {console.log('3. Callback done: ', param); return param;})
}



function getApiBaseUrl(_callBack) {
  console.log('1. Enter getApiBaseUrl');
  fetch('https://official-joke-api.appspot.com/jokes/programming/random')
  .then(response => response.json())
  .then( data => {
    console.log('2. Data fetched: ', data[0].type);
    _callBack(data[0].type);
  })    
  .catch(err => {
    console.error(err);
  })
}


// This where it fails to "wait"
console.log('4. This should not be undefined: ', dynConfig.apiUrl);

jsfiddle

As per our discussion in the comments here is an implementation with both async/await and promises

Async/Await based

/* Async/Await */
async function async_getApiBaseUrl() {
    try {
    let res = await (await fetch('https://official-joke-api.appspot.com/jokes/programming/random')).json();

    return res[0];

  } catch(err) {
    console.error(err);
    return '';
  }
}

async_getApiBaseUrl().then(function(joke){
  console.log('async joke:')
  console.log(`Got a joke: ${joke.setup}`);
  console.log(joke.punchline);
  console.log(' ');
});

Promise based

/* Promise */
function promise_getApiBaseUrl(_callBack){
    return new Promise(function(resolve, reject) {
    fetch('https://official-joke-api.appspot.com/jokes/programming/random')
        .then(async function(res) { return await res.json(); })
        .then(function (res) {
          resolve(res[0]);
      })
      .catch(function (err) { reject(err) });
  });
}

promise_getApiBaseUrl()
    .then(function(joke) {
    // use your apiBaseUrl
    console.log('promise joke:')
    console.log(`Got a joke: ${joke.setup}`);
    console.log(joke.punchline);
  })
  .catch(function(err){
    console.error(err);
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM