首页 > 解决方案 > 为什么履行的诺言没有定义?

问题描述

你能给我解释一下吗?

const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    if(true) {
      resolve('succes')
    } else {
      reject('failure')
    }
  }, 4000)
})

promise1.then(result => console.log(result))

为什么在那之后我在控制台上获得了“成功”之类的东西

Promise {<fulfilled>: undefined}

如果我的承诺返回“成功”字符串值,为什么会有未定义?这是因为 setTimeout 嵌套?我该如何解决这个问题?

标签: javascriptasynchronouspromiseundefined

解决方案


通过进行以下调整:

const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    if(true) {
      resolve('succes')
    } else {
      reject('failure')
    }
  }, 4000)
})

promise1.then(result => {
  console.log(result);
  return result;
})

您将在开发工具上同时拥有 log 和 promise 返回值;

为什么?

undefined是隐式返回值回调( return;)的结果,当函数没有显式返回任何内容时,js引擎会return在函数体的末尾添加隐式语句。


推荐阅读