【问题标题】:Returning an actual Promise from an async function从异步函数返回一个实际的 Promise
【发布时间】:2020-07-09 14:08:24
【问题描述】:

我了解异步函数本身会返回一个 Promise。我想知道如何作为已解决的异步函数承诺(可以说是嵌套承诺)的结果返回另一个承诺。如果不可能,我对此原因很感兴趣。

以下是一些示例代码,其中一些对象属性丢失。

function B() {
    return new Promise((resolve) => {
        setTimeout(() => resolve('B resolved'), 10);
   })
}

async function A() {
    const result = new Promise((resolve) => { setTimeout(() => resolve('A resolved'), 30); }); 
    result.test = 'test';
    result.b = await B();
    return result;
}

const a = A();
console.log('a.b', a.b); // expected undefined, correct
console.log('test1', a.test); // expected undefined, correct

a.then((a_data) => {
    console.log('a_data', a_data); // expected Promise constructed in A(), actually 'A resolved'
    console.log('a_data.b', a_data.b); // expected 'B resolved', actually undefined
    console.log('a_data.test', a_data.test); // expected 'test', actually undefined
	
    // this code expected to be allowed, but .then is not a member of a_data since it's not a promise
    // a_data.then((data) => {
    //     console.log(data); // expected 'A resolved'
	// });
});

我也明白,在大多数情况下,最好等待 A() 中定义的 Promise 解决后再提供结果,但是,这不是我要寻找的答案。

'result' 对象只要不是 Promise 就按预期返回,否则 'result' 承诺会被解析,额外的属性 'test' 和 'b' 会丢失。

【问题讨论】:

  • 您正在向 promise 对象添加值,当您调用该对象时,它只会返回已解析的对象而不是整个对象。

标签: javascript promise async-await


【解决方案1】:

您将它们添加到 promise 对象上,当它得到解决时,它只返回从已解决函数返回的值,因此您丢失了 test 和 b,如果您需要 test 和 b 从返回的值承诺的对象,您需要从解析函数中返回它们。

function B() {
  return new Promise((resolve) => {
    setTimeout(() => resolve('B resolved'), 1000);
  })
}

async function A() {
  const result = new Promise((resolve) => {
    setTimeout(() => resolve({
      test: "test",
      b:  B()
    }), 3000);
  });

  return result;
}

const a = A();
console.log('a.b', a.b); // expected undefined, correct
console.log('test1', a.test); // expected undefined, correct

a.then((a_data) => {
  console.log('a_data', a_data); // expected Promise constructed in A(), actually 'A resolved'
  console.log('a_data.b', a_data.b.then(v=> console.log(v))); // expected 'B resolved', actually undefined
  console.log('a_data.test', a_data.test); // expected 'test', actually undefined

  // this code expected to be allowed, but .then is not a member of a_data since it's not a promise
  // a_data.then((data) => {
  //      console.log(data); // expected 'A resolved'
  // });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 2023-03-08
    • 2023-03-13
    • 2021-12-29
    • 2020-07-09
    • 2017-10-16
    • 1970-01-01
    相关资源
    最近更新 更多