我正在使用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()});
})();
答案 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)
await
从Promise
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
。