简体   繁体   English

调用Resolve函数转到JavaScript Promise中的Reject函数

[英]Calling Resolve function goes to Reject function in JavaScript Promise

I have the following code: 我有以下代码:

return new Promise (function (resolve,reject) {
        if (this.ImageData && averageColor) {
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
                    console.log("Image found");
                    resolve(xhr.response);
                }else {
                    console.log("Image not found");
                    reject();
                }
            }
            xhr.open('GET', 'http://localhost:8765/color/'+averageColor, true);
            xhr.send(null);
        }
        else {
            reject();
        }
    });

The function that calls this code is as follows: 调用此代码的函数如下:

var v =  tile.getImage(tile.getColorAverage());
        v.then(function (value) {
            console.log("laughing");
        }).catch(function () {
           console.log("Catch called");
        });

The issue is in my promise I can see that it is going in that if condition and getting the response from the server correctly (because of the console.log). 问题在于我的承诺,如果出现这种情况,并且可以正确地从服务器获取响应(由于console.log)。 However, on the other side, it doesn't go into 'then' bit of promise at all (not even once). 但是,另一方面,它根本就没有“那么”的承诺(甚至没有一次)。 It goes to the reject one for some reason. 由于某种原因,它被拒绝了。 I am going nuts as I can see it executes the bit which is supposed to resolve it but I don't get anything in then. 我疯了,因为我看到它执行了应该解决的位,但那时我什么也没得到。 Any help would be much appreciated. 任何帮助将非常感激。

Edited: 编辑:

Now I just ran it once. 现在,我只运行了一次。 And here is my console.log trace. 这是我的console.log跟踪。 Now even more confused: 现在更加困惑:

在此处输入图片说明

xhr.onreadystatechange = function () {
    if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
        console.log(xhr.response);
        resolve(xhr.response);
    }else {
        reject();
    }
}

The thing about onreadystatechange is, it gets called MULTIPLE times 关于onreadystatechange的事情是,它被称为MULTIPLE次

The thing about promise resolution is that once rejected or resolved, it can not be rejected or resovled again 关于承诺解决的问题是,一旦被拒绝或解决,就不能再次被拒绝或重新解决

The first time onreadystatechange gets called, the status would be 1, not 4 ... so you reject 第一次调用onreadystatechange时,状态将为1,而不是4 ...因此您拒绝了

you should only reject if status is 4 and (DONE) AND status != 200 您仅应在状态为4且(完成)AND状态!= 200时拒绝

xhr.onreadystatechange = function () {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        if(xhr.status == 200) {
            console.log(xhr.response);
            resolve(xhr.response);
        } else {
            reject();
        }
    }
}

Alternatively, use onload/onerror - though you still need to check for status == 200 in onload 或者,使用onload / onerror-尽管您仍然需要检查onload中的状态== 200

xhr.onload= function () {
    if(xhr.status == 200) {
        console.log(xhr.response);
        resolve(xhr.response);
    } else {
        reject();
    }
}


xhr.onerror= function () {
    reject();
}

as a side note about something that works but looks wrong 作为一些有用但看起来错误的东西的旁注

return new Promise (function (resolve,reject) {
    if (this.ImageData && averageColor) {

this inside the promise constructor callback could be window , or it even could even be undefined in strict mode - you need to fix that code before it causes issues down the track this诺言构造回调里面可能是window ,或者甚至有可能甚至undefined严格模式-你需要修复这些代码是导致问题走下赛场前

The reason you are having this issue is that onreadystatechange is called multiple times before the request completes and before it is DONE you will get your else condition which calls reject . 您遇到此问题的原因是,在请求完成之前多次onreadystatechange ,在请求完成之前,您将获得else条件,该条件将调用reject You should only reject if DONE AND xhr.status != 200 . 仅应在DONE AND xhr.status != 200拒绝。 Here is an example: 这是一个例子:

if (xhr.readyState == XMLHttpRequest.DONE) {
    if (xhr.status == 200) {
        resolve(xhr.response);
    } else {
        reject();
    }
}

this within Promise constructor is window , unless specifically set to a different value. 除非专门设置为其他值,否则Promise构造函数中的thiswindow this.ImageData would evaluate to false without setting this to the object that has .ImageData as a property at call to new Promise() . this.ImageData将评估为false不设置this到有物体.ImageData作为属性在调用new Promise()

Substitute reference to object that has property ImageData for this.ImageData within Promise constructor resolver function. Promise构造函数解析器函数中,替代对具有this.ImageData属性的ImageData对象的引用。

For example 例如

function resolver(resolve, reject) {

}

new Promise(resolver.bind(/*object that has `.ImageData` as property*/))

Also, substitute load event for readystatechange event and include error event handler for XMLHttpRequest object. 另外,将load事件替换为readystatechange事件,并为XMLHttpRequest对象添加error事件处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 JavaScript Promise解析并拒绝函数调用序列 - JavaScript Promise resolve and reject function call sequence 命名函数不能解决或拒绝承诺 - named function does not resolve or reject promise Promise的解决和拒绝功能的返回类型是什么? - What is the return type of resolve and reject function of a Promise? 在另一个函数中解析/拒绝jQuery Promise - resolve/reject jquery promise in another function 在JavaScript中承诺解决并拒绝 - Promise resolve and reject in javascript 内部函数args不可见返回new Promise(function(resolve,reject) - function args not visible inside return new Promise(function(resolve, reject) 蓝鸟承诺:新的Promise(函数(解决,拒绝)中是否可以有多个拒绝()? - Bluebird Promise: Is is possible to have multiple reject() in new Promise(function (resolve, reject)? 将带有解析和拒绝的承诺转换为异步函数的正确方法(puppeteer) - proper way to convert promise with resolve & reject to async function (puppeteer) 我可以用Promise的解决/拒绝控制功能的流程吗? - Can I control the flow of a function with a Promise's resolve / reject? 解决/拒绝后解决/拒绝承诺垃圾收集的功能? - Is resolve/reject function of promise garbage-collected after resolution/rejection?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM