将函数的返回值调用到其他函数

时间:2018-06-12 11:25:08

标签: javascript function

如何正确返回变量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 :(得分:1)

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
     })

}

答案 1 :(得分:0)

如果您可以修改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);
}