如何从承诺中获得结果

时间:2021-06-30 10:17:57

标签: javascript promise

我有 Promise 但不知道如何从中获取字符串“foo”。可能是我的承诺不正确。

const bar = new Promise((res, rej) => res("foo"));
then((result) => {
  return result;
});

3 个答案:

答案 0 :(得分:1)

const bar = new Promise((res) => res("foo"))
.then((result) => {
  console.log(result)
});

? 在单词 . 之前需要一个句点 (then) -> .then

thenPromise 的方法,因此需要 .then 来调用该方法。 then 不是一个独立的全局函数。


当你这样做时:

new Promise((res) => res("foo")).then((result) => ...

任何 then 只会在 Promise 被解决时触发。

Promise 在内部注册所有 then 方法并在您执行 res("foo") 时调用它们(在您的情况下),所以这就是您需要 {{1} } - 注册这些回调,当/如果承诺被解决

答案 1 :(得分:0)

你应该这样做:

const bar = new Promise((res, rej) => res("foo"));

bar.then((result) => {
     console.log(result);
    // do whatever you want to do with result
}).catch(err=>console.log(err))

then 处理程序在承诺解决时被调用。 当承诺被拒绝时调用 catch 处理程序。

答案 2 :(得分:0)

您将 Promise 分配给变量 bar。如果您想要该值,您应该then Promise 如下所示:

const bar = new Promise((res, rej) => res("foo")).then((result) => {
  console.log(result)
});

添加 catch 语句来处理错误也是一个好习惯。

最后,如果您是 Promises 的新手,Google 提供的 Udacity 上的 this free course 将帮助您更好地理解 Promises。