如何在 fetch 函数中更新 es6 中的变量?

how to update a variable in es6 inside a fetch function?

我有以下代码:

let courses = '';

fetch(link)
.then(function(response) {
  return response.json();
}).then(function(json) {
  courses = json;
}).catch(function(ex) {
  console.log('parsing failed', ex);
});

使用 console.log(courses) 打印出 ''。

如何将其设置为检索到的json?

fetch方法是异步的,本质上,你只能访问fetchpromise之后的courses变量中的json内容解决。尝试执行以下操作:

function synchronousCode(courses) {
  console.log('courses', courses); // output json courses
}

fetch(link)
.then(function(response) {
  return response.json();
})
.then(synchronousCode)
.catch(function(ex) {
  console.log('parsing failed', ex);
});

使用 Fetch API 的好处之一是您可以整齐地链接您的方法,而不是只有一个“synchronousCode”函数。这是一个例子:

function asynchronouslyAnalyze(courses) {
  return new Promise(function(resolve, reject) {
    setTimeout(function () { resolve(courses) }, 1000);
  });
}

function parse(courses) {
  // do something with courses
  return courses;
}

function print(courses) {
  console.log('courses', courses); // output courses json
}

function toJSON(response) {
  return response.json();
}

fetch(link)
.then(toJSON)
.then(asynchronouslyAnalyze)
.then(parse)
.then(print)
.catch(function(ex) {
  console.log('parsing failed', ex);
});

希望对您有所帮助!