【问题标题】:Return multiple variables on async/await在 async/await 上返回多个变量
【发布时间】:2018-02-15 19:50:39
【问题描述】:

我想知道是否有办法在不返回数组或 JavaScript 对象的情况下获取第二个 resolve 值 (test2)。

function testFunction() {
  return new Promise(function(resolve, reject) {
    resolve("test1", "test2");
  });
}

async function run() {
  var response = await testFunction();
  console.log(response); // test1
}

run();

【问题讨论】:

  • 那么您希望response 变成什么?
  • 我不明白你为什么要避免返回数据结构(一个对象),这就是 JavaScript 是如何构造来做这些事情的。
  • @MaciejSikora @Bergi,我想知道是否有内置功能,因为如果您在没有 async/await 的情况下构造函数调用,这两个变量都可用:testFunction().then(function(response1, response2) {...})
  • @MarkNijboer 不,他们不是。至少不是标准的 ES6 承诺,它只有一个结果值。

标签: javascript asynchronous async-await es6-promise


【解决方案1】:

您只能传递一项。但是从ES6 开始,有一个很好的功能叫做Array Destructuring

返回一个数组,您可以将属性分配留在后台。

function testFunction() {
    return new Promise(function(resolve, reject) {
  	       resolve([ "test1", "test2"] );
           });
}

async function run() {

  const [firstRes, secondRes] = await testFunction();
  
  console.log(firstRes, secondRes);

}

run();

【讨论】:

  • 我刚刚发现 const { response1, response2 } = await testFunction(); 在 Node.js 8 中工作。它也被 util 模块中的 promisify 方法使用。所以没有必要返回一个数组:-)
  • 作为对象返回对我不起作用。在上面的示例中,我得到 response1 和 response2 的“未定义”。但它在作为数组返回时有效。知道为什么吗? @马克
猜你喜欢
  • 2021-09-22
  • 1970-01-01
  • 2018-06-27
  • 2019-06-27
  • 2017-09-11
  • 2019-05-30
  • 2021-08-06
  • 2013-02-27
相关资源
最近更新 更多