[英]promise then is not the function error for Node Promise
I am using async/await
to return the Promise
, to use it as promoise in node script. 我正在使用
async/await
返回Promise
,以将其用作节点脚本中的promoise。 When I am trying to make use of the return value as Promise
, its giving a error a.then is not a function
当我尝试使用返回值作为
Promise
,它给出了错误a.then is not a function
here is the sample code 这是示例代码
function test () {
//do something .......
//....
return global.Promise;
}
(async ()=> {
let a = await test();
a.then(()=> { console.log('good ')}, (err)=> { console.log()});
})();
The Promise constructor function isn't a promise, it is a tool to make promises with. Promise构造函数不是一个承诺,它是一个实现承诺的工具。
Even if it was a promise, since you are await
ing the return value of test
, it would have been resolved into a value before you try to call then
on it. 即使这是一个承诺,因为你
await
荷兰国际集团的返回值test
,它会被你在打电话前分解为一个值then
就可以了。 (The point of await
is that it replaces the use of then()
callbacks). (
await
点是它取代了then()
回调的使用)。
You can await a function that returns a promise like this: 您可以等待一个返回promise的函数,如下所示:
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();
If you change the true
to false
you can test the "resolve" case. 如果将
true
更改为false
,则可以测试“解决”情况。
await
retrieves the resolved value from a Promise
await
从Promise
检索解析的值
let a = await test(); // `a` is no longer a Promise
I've put together two ways of retrieving values from a Promise
我汇总了两种从
Promise
检索值的方法
using await 使用等待
(async () => {
try {
let a = await test();
console.log('Good', a);
} catch(err) {
console.log(err);
}
})();
using .then() 使用.then()
test().then(a => {
console.log('Good', a);
}).catch(err => {
console.log(err);
});
Please note that, the async
arrow function is removed because there is no await
needed. 请注意,因为不需要
await
,所以删除了async
箭头功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.