P5.js中loadJSON的回调函数如何获取return的值

How get return of value from the callback function of loadJSON in P5.js

通常我有 Javascript 和 P5.js 的代码:

只是为了从 url 获取数据并与其他函数一起使用,甚至不需要多次重新加载它。

function setup() {
  var main = document.getElementById('main');
  var start = document.createElement('button');
  main.appendChild(start);
  start.setAttribute('onclick', 'go()');
  // consideration of create TextNode of start button
}

function go() {
  loadJSON('url', treatData);
}

function treatData(data) {
  var arr = [];
  arr.push(data);

  var btn = document.createElement('button');
  //consideration of append btn var and create TextNode of it

  btn.setAttribute('onclick', 'get()');

  return arr;
}

function get() {
 // when i call treateData() here it is not work. 
  // so how get arr here;
}

除了将 treatData() 函数用作对 loadJSON() 函数的回调之外,您不想从任何地方调用它。

如果您想访问加载的数据,可以将其存储在变量中。像这样:

var arr;

function go() {
  loadJSON('url', treatData);
}

function treatData(data) {
  arr = data;
}

function get() {
  console.log(arr);
}