Вызов возвращаемого значения функции другой функции - PullRequest
0 голосов
/ 12 июня 2018

Как правильно вернуть значение переменной otherURL и вызвать / использовать его в другой функции того же файла.

Используя код ниже.

function getOtherURL() {
    var url = "https://url/data.json";

    fetch(url)
    .then(res => res.json())
    .then((data) => {
        console.log('Checkout this JSON! ', data);
        let otherURL;

        for (var i = 0; i < data.length; i++) {
        //some code
            otherURL = "http://url/from" + from + "&to=" + to;
        }
        console.log("otherURL" , otherURL);
    })
    .catch(err => { throw err });
}

Это моя другая функция

export function getData() {
    //need to read the value of otherURL and assign into new variable something like this
    let newURL = otherURL;
    const promiseMSFT = fetch(newURL) //here I want to assign the newURL
    .then(response => response.json())
    .then(data => {
    //more code

}

Ответы [ 2 ]

0 голосов
/ 12 июня 2018

Если вы можете изменить функцию getData(), чтобы иметь такой параметр, как getData(otherURL), вы можете сделать это:

function getOtherURL() {
      const url = 'https://url/data.json';

      fetch(url)
    .then(res => res.json())
    .then((data) => {
      console.log('Checkout this JSON! ', data);
      let otherURL;

      for (let i = 0; i < data.length; i++) {
        // some code
        otherURL = `http://url/from${from}&to=${to}`;
      }
      console.log('otherURL', otherURL);
      return otherURL;
    })
    .then(otherURL => {
    // chain then() here
      getData(otherURL);
    })
    .catch((err) => {
      throw err;
    });
}

Измененная функция

export function getData(otherURL) {
  // need to read the value of otherURL and assign into new variable something like this
  let newURL = otherURL;
  console.log(newURL);
}
0 голосов
/ 12 июня 2018
function getOtherURL() {
  var url = "https://url/data.json";
  return fetch(url)
  .then(res => res.json())
  .then((data) => {
    console.log('Checkout this JSON! ', data);
    let otherURL;
    for (var i = 0; i < data.length; i++) {
      //some code
      otherURL = "http://url/from" + from + "&to=" + to;
    }
    return otherUrl; //return value
  })
  .catch(err => { throw err });
}

и затем вызовите его в экспортируемой функции

export function getData() {
    //return promise to the caller
    return getOtherURL().then(otherUrl => {
      let newURL = otherURL;
      //then you can chain the other promise
      return fetch(newUrl);
    })
    .then(response => response.json())
    .then(data => {
       //more code
     })

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...