然后保证不是Node Promise的功能错误

时间:2019-07-11 22:28:14

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

我正在使用async/await返回Promise,以用作节点脚本中的促销。当我尝试将返回值用作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()}); 
})();

3 个答案:

答案 0 :(得分:2)

Promise构造函数不是一个Promise,而是一个用来实现Promise的工具。

即使这是一个承诺,由于您正在await使用test的返回值,因此在尝试对其调用then之前,它已经被解析为一个值。 (await的要点是它替换了使用then()回调)。

答案 1 :(得分:0)

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

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,则可以测试“解决”情况。

答案 2 :(得分:0)

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