← Back To API Reference

Promise.try

Promise.try(function() fn) -> Promise
Promise.attempt(function() fn) -> Promise

使用 Promise.try 启动 promises 链。任何同步异常都将在返回的 promise 中被拒绝。

function getUserById(id) {
    return Promise.try(function() {
        if (typeof id !== "number") {
            throw new Error("id must be a number");
        }
        return db.getUserById(id);
    });
}

现在,如果有人使用这个函数,他们将会在的 Promise .catch 中捕获所有的错误,而不是同时处理同步和异步异常流。

为了与早期的 ECMAScript 版本兼容,为 Promise.try 提供了别名 Promise.attempt