首页 > 解决方案 > 调用一个函数的返回值给另一个函数

问题描述

如何正确返回变量的值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

}

标签: javascriptfunction

解决方案


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

}

推荐阅读