Js 调用一个方法需要等数组被赋值了才往下走
可以使用回调函数或者Promise来实现等待数组被赋值后再继续执行的功能。
使用回调函数的方法如下:
function doSomethingWithArray(callback) {
  // 假设这里是异步操作获取数组的值
  setTimeout(function() {
    const array = [1, 2, 3];
    callback(array);
  }, 1000);
}
// 调用方法,传入回调函数
doSomethingWithArray(function(array) {
  // 在回调函数中处理数组
  console.log(array);
  // 继续执行其他操作
});
使用Promise的方法如下:
function doSomethingWithArray() {
  return new Promise(function(resolve, reject) {
    // 假设这里是异步操作获取数组的值
    setTimeout(function() {
      const array = [1, 2, 3];
      resolve(array);
    }, 1000);
  });
}
// 调用方法,使用then方法处理Promise返回的结果
doSomethingWithArray().then(function(array) {
  // 在回调函数中处理数组
  console.log(array);
  // 继续执行其他操作
});
无论是使用回调函数还是Promise,都是在获取到数组值后执行回调函数或者在then方法中处理返回的结果,从而实现等待数组被赋值后再往下走的功能
原文地址: https://www.cveoy.top/t/topic/hLku 著作权归作者所有。请勿转载和采集!