javascript Promise 不是构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30033079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Promise is not a constructor
提问by baao
I'm trying to use a promise but get a type error: Promise is not a constructor.
我正在尝试使用 Promise,但出现类型错误:Promise 不是构造函数。
Here's the promise:
这是承诺:
var Promise = new Promise(
function (resolve,error) {
for (var key in excludeValues) {
/* some ifs */
minVal = someValue
........
........
}
resolve(errors)
});
Promise.then(
function(data){
if (minVal > maxVal)
{
errors.minMax.push(
'minMax'
)
}
if (gapVal > minVal * -1)
{
errors.minMax.push(
'gapVal'
)
}
return (errors.minMax.length == 0 && errors.zahl.length == 0 && errors.hoch.length == 0 && errors.niedrig.length == 0)
}
);
Can someone tell me what I'm doing wrong?
有人可以告诉我我做错了什么吗?
回答by Bergi
With var Promise
you declare a local variable in your scope. It is initialised with undefined
and shadowsthe global Promise
constructor. Use a different variable name
随着var Promise
你在你的范围内声明一个局部变量。它使用全局构造函数初始化undefined
并隐藏它Promise
。使用不同的变量名
var promise = new Promise(…);
promise.then(…);
or none at all
或者根本没有
new Promise(…).then(…);
回答by Giridhar Prakash Yellapu
problem is you are overwriting Promise function, so when you execute code second time "Promise" is not function anymore.
问题是您正在覆盖 Promise 函数,因此当您第二次执行代码时,“Promise”不再起作用。
so change variable name as shown below
所以更改变量名,如下所示
var promisevariable = new Promise(
function (resolve,error) {
for (var key in excludeValues) {
/* some ifs */
minVal = someValue
........
........
}
resolve(errors)
});
回答by Chris Halcrow
I had a very similar problem that gives an almost identical error message. I declared:
我有一个非常相似的问题,它给出了几乎相同的错误消息。我宣布:
var promise = new promise (...)
instead of new Promise(...)
.
var promise = new promise (...)
而不是new Promise(...)
.
That mistake will give a very similar error message, as follows:
该错误将给出非常相似的错误消息,如下所示:
promise is not a constructor
(note the lowercasepromise
).
promise is not a constructor
(注意小写promise
)。
In this case, the error is because you're referencing the variable you've declared (promise
), instead of invoking the Promise
constructor.
在这种情况下,错误是因为您引用了您声明的变量 ( promise
),而不是调用Promise
构造函数。