首页 > 解决方案 > 如何在 Firefox 控制台中等待 promise 解决

问题描述

我在 Firefox 中打开了开发者控制台,并且必须使用一些承诺。我真的很喜欢一些阻塞语法,它只是等待承诺解决并直接返回结果。现在我必须做类似的事情:

var result; promise.then((res) => { result = res})

每次我真的厌倦了。我试过这样的事情:

resolve = function(promise) { var res; var done = false; promise.then(r => {res = r; done = true}); while(!done) {}; return res; }

但它永远卡住了。有什么 - 任何东西,如何轻松获得结果?

编辑:首先,我不是在处理 Node 环境或一些 JS 脚本。我知道如何在那里对付他们。我正在处理 Fixrefox 开发工具控制台,我正在寻找一些简单的方法来等待承诺解决。我知道我可以做 IIFE。这可以针对一两个 Promise 完成,但不能针对其中的十几个 Promise,因为那是很多代码。我想要类似的东西:

function = resolvePromise(promise) { ... };

它只是阻塞,直到 promise 被解决并返回已解决的值。所以我可以简单地使用它:

var result = resolvePromise(promise); // result now holds the actual value

它不一定是函数,也可以是一些 hack,因为它不会在脚本或 Node 中使用,而只能在开发工具中使用。在控制台中为每个 promise 编写 IIFE 简直是可怕的人体工程学。

Edit2:@Andy 建议使用 Promise.all 但因为我没有同时拥有所有的承诺,所以这不是一个选择。基本上我在一个 REPL 中,我需要一种简短而简单的方法来评估/检查/存储/决定下一步做什么,然后重复。我不能一直写 IIFE

谢谢

标签: javascriptfirefoxpromise

解决方案


async/await是解决此问题的最佳现代方法。

// Mock fetch function to return data
// after 2s
function fetch() {
  const n = Math.floor(Math.random() * (100 - 1) + 1);
  return new Promise(resolve => {
    setTimeout(() => resolve(n), 1000);
  });
}

// Push a load of promises into an array
const arr = [];
for (let i = 0; i < 20; i++) {
  arr.push(fetch());
}

// async immediately-invoked function expression.
// `Promise.all` gathers up all the results of all
// the promises in the array and returns its own promise
// and `await` pauses until that promise resolves
(async () => {
  console.log('Please wait for the result');
  const result = await Promise.all(arr);
  console.log(result);
})();


推荐阅读