【问题标题】:Extract value from a promise without a .then() [duplicate]从没有 .then() 的承诺中提取价值 [重复]
【发布时间】:2020-09-03 18:33:42
【问题描述】:

我想知道是否有办法获取承诺的返回值并将其直接分配给 .then() 调用之外的变量并使用它?

这是我的实现。

const name = "Jane"
const age = 34

// Promise 1
function getName() {
    return new Promise(function prom(resolve, reject) {
        setTimeout(function () {
            resolve(name) // "Jane"
        }, 5000)
    })
}

// Promise 2
function getAge() {
    return new Promise(function prom(resolve, reject) {
        setTimeout(function () {
            resolve(age) // 34
        }, 1500)
    })
}

// Promise all
function getValue(cb) {
    return Promise.all([
        getName() /* Jane */,
        getAge() /* 34 */
    ])
        .then(cb, cb)
}

以上所有我尝试这样做:

const x = getValue(x => x)[1] // 34
const sum = x + 1; // 35

有什么想法吗?或者这可能吗?

谢谢!

【问题讨论】:

  • await 提供了一些语法糖来做到这一点。
  • Await 不能在异步函数的执行上下文之外使用!它可能在 Deno 中工作,因为 await 可以在顶层使用,但在 vanilla JS 中我不确定。
  • 除了“这感觉很奇怪,我想摆脱它”之外,还有什么特别的原因让您感到疑惑?
  • 不,这是不可能的。您实际上是在问“有没有办法立即从未来获得价值?”。

标签: javascript asynchronous promise es6-promise


【解决方案1】:

您可以使用 async/await 以同步方式编写此代码并降低代码的复杂性。 async/await 不是在 Promise 上使用 then(),而是提供了一种以同步方式编写异步代码的方法,并且也很容易理解。

尝试以下替代代码:

const name = "Jane"
const age = 34

// Promise 1
function getName() {
    return new Promise(function prom(resolve, reject) {
        setTimeout(function () {
            resolve(name) // "Jane"
        }, 5000)
    })
}

// Promise 2
function getAge() {
    return new Promise(function prom(resolve, reject) {
        setTimeout(function () {
            resolve(age) // 34
        }, 1500)
    })
}

// Promise all
async function getValue() { /*To use await, function should start with async keyword*/
    const userName = await getName();  /*Next line will not be executed until response is received here*/
    const userAge = await getAge();
    return Promise.all([
        userName /* Jane */,
        userAge /* 34 */
    ])
}

async function main(){
    const x =(await getValue())[1] // 34
    const sum = x + 1; // 35
    console.log(sum)
}

main()

请参阅 async/await 主题以更好地理解此概念。

【讨论】:

  • Promise.all 的调用毫无意义。
  • @Bergi 为什么不呢?
  • 因为Promise.all 需要一组承诺,但userNameuserAge 都不是承诺。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-21
  • 2017-06-05
  • 1970-01-01
  • 1970-01-01
  • 2019-04-26
  • 2018-05-16
相关资源
最近更新 更多