javascript - 如何让该 if 语句在其余代码运行之前完成执行?

标签 javascript

这是我在应用程序中尝试执行的操作的简单版本。我有一个 if 语句,它评估函数调用的结果,然后如果该语句返回 true 则填充一个数组。在 if 语句完全完成后,我想运行更多代码,例如 console.log,如下所示。

我知道 if 的评估需要很长时间才能完成,而 javascript 由于其异步性而只是继续到 console.log。如何让代码等待 if 语句完成?

var tabs = [];

if (isTrue()) {
    tabs.push('some string');
}

console.log(tabs[1]);

function isTrue() {
    setTimeout(function() {
        return true;
    }, 500)
}

最佳答案

您可以将代码包装在 Promise 中并通过调用 then 消耗返回值关于它:

var tabs = [];
isTrue().then(res => {
  if (res) {
    tabs.push('some string');
  }
  return tabs;
}).then(arr => {
  console.log(arr);
});



function isTrue() {
  //Just wrap your existing code in a Promise constructor
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      //Pass whatever value you want to consume later to resolve
      resolve(true);
    }, 500)
  });
}

关于javascript - 如何让该 if 语句在其余代码运行之前完成执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54497998/

相关文章:

javascript - 从数组中获取值时,SQLite DELETE 事务不起作用

javascript - 像 HTMLParagraphElement 这样的原型(prototype)对象位于 BOM 树中的什么位置?

javascript - 在 React Native 中创建行

javascript - 是否可以使用 grunt-contrib-uglify 排除部分 javascript?

javascript - 如何检查数组中是否存在 jQuery 对象?

javascript - 检测鼠标滚轮滚动的次数

javascript - 使用 ES6 语法动态导入 JavaScript 模块?

javascript - 使用 addEventListener 的处理程序中 "this"的值

javascript - 为什么 jquery 代码没有在 jsfiddle 中运行

javascript - 使用 Node.js 的 fs.watchfile 的相对路径