【问题标题】:promise then is not the function error for Node Promisepromise then 不是 Node Promise 的函数错误
【发布时间】:2019-07-12 15:04:02
【问题描述】:

我正在使用 async/await 返回 Promise ,将其用作节点脚本中的 promoise。当我尝试将返回值用作 Promise 时,它会给出错误 a.then is not a function

这里是示例代码

function test () {

        //do something .......
        //....
        return global.Promise;

}

(async ()=> {

    let a = await test();
    a.then(()=> { console.log('good ')}, (err)=> { console.log()}); 
})();

【问题讨论】:

  • 您可以使用return Promise.resolve( );,但您还需要删除await 以使a 成为promise。

标签: javascript node.js promise async-await es6-promise


【解决方案1】:

Promise 构造函数不是一个 Promise,它是一个用来做出 Promise 的工具。

即使它是一个承诺,因为你是 awaiting test 的返回值,它会在你尝试调用 then 之前解析为一个值。 (await 的意义在于它替换了then() 回调的使用。

【讨论】:

    【解决方案2】:

    您可以等待一个返回如下承诺的函数:

    function test() {
      return new Promise((resolve, reject) => {
        if (true) {
          reject("Custom error message");
        }
        setTimeout(() => {
          resolve(56)
        }, 200);
      })
    }
    
    async function main() {
      try {
        const a = await test();
        console.log(a)
      } catch (e) { // this handles the "reject"
        console.log(e);
      }
    }
    
    main();
    

    如果您将true 更改为false,您可以测试“解决”案例。

    【讨论】:

      【解决方案3】:

      awaitPromise 检索解析值

      let a = await test(); // `a` is no longer a Promise
      

      我总结了两种从 Promise 中检索值的方法

      使用等待

      (async () => {
          try {
              let a = await test();
              console.log('Good', a);
          } catch(err) {
              console.log(err);
          }
      })();
      

      使用 .then()

      test().then(a => {
          console.log('Good', a);
      }).catch(err => {
          console.log(err);        
      });
      

      请注意,async 箭头函数已被删除,因为不需要 await

      【讨论】:

        猜你喜欢
        • 2019-02-14
        • 2023-03-05
        • 2020-10-22
        • 2018-02-28
        • 1970-01-01
        • 1970-01-01
        • 2017-10-08
        • 2021-03-17
        • 1970-01-01
        相关资源
        最近更新 更多