使用新的异步/等待语法,您可以实现此目的。请注意,在编写本文时,并非所有浏览器都支持此功能,您可能需要使用babel(或类似的东西)来转换代码。
// Because of the "async" keyword here, calling getSomevalue()// will return a promise.async function getSomevalue() { if (somethingIsNotOk) { throw new Error('uh oh'); } else { return 'Yay!'; }}async function() { try { // "await" will wait for the promise to resolve or reject // if it rejects, an error will be thrown, which you can // catch with a regular try/catch block const somevalue = await getSomevalue(); doSomethingWith(somevalue); } catch (error) { console.error(error); }}


