【问题标题】:How to return values from a promise and async / await function in Node.js如何从 Node.js 中的 promise 和 async / await 函数返回值
【发布时间】:2019-11-06 15:16:44
【问题描述】:

我是 Node.js 的新手并承诺。我在 C# 中使用 async/await 完成了一些工作,但我在努力获取返回值。我按照stackoverflow上的一个示例并将其复制到下面。我稍微修改了它以代表我正在尝试做的事情,但它不起作用。我希望有人能告诉我我错过了什么。我创建了两个示例:一个带有 promise,另一个使用 async。感谢您的帮助!

let bar;
function foo() {
    return new Promise((resolve, reject) => { 
        setTimeout(function () {        
            resolve('wohoo')
        }, 1000)
    })
}

async function foo2() {
    setTimeout(function () {
        return ('wohoo')
    }, 1000);
}

function test3() {
    foo().then(res => {
        bar = res;
        console.log(bar) 
    });
}

async function test4() {
    let bar2 = await foo2();
    console.log('bar2=', bar2);
}

test3();
test4();
console.log('bar=', bar);
console.log('The end.');


The Output:
-----------
bar= undefined
The end.
bar2= undefined
wohoo


【问题讨论】:

  • 这里的部分问题可能是您在多个异步函数中使用相同的变量bar,并且它可能会意外更改...
  • 这是我引用的那个。如果你使用 foo().then(res => {bar = res; console.log(bar); });但是如果你像我在 test3() 中那样将它包装在一个函数中,它不会设置 bar。
  • bar 只在 test3() 中使用,bar2 只在 test4() 中使用。根据您的建议,我使它们完全不同,但仍然存在相同的问题。

标签: javascript node.js promise async-await


【解决方案1】:

形式承诺:

var promise1 = new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve('foo');
  }, 300);
});

promise1.then(function(value) {
  console.log(value);
  // expected output: "foo"
});

【讨论】:

  • 请在你的回答中添加一些解释!
猜你喜欢
  • 2019-03-01
  • 1970-01-01
  • 2021-08-06
  • 2018-03-27
  • 1970-01-01
  • 2020-11-19
  • 2017-09-11
  • 1970-01-01
相关资源
最近更新 更多