gpt4 book ai didi

JavaScript Promise 卡在 resolve 上

转载 作者:搜寻专家 更新时间:2023-11-01 05:23:11 25 4
gpt4 key购买 nike

我有一个异步函数,我执行了多次 (2),但由于某种原因,promise 卡在了 resolve 上。它执行 resolve(),但不执行任何操作。

函数如下(基本上是从 URL 创建一个 blob):

function getBlobAt(url, callback) {
console.log("New getBlobAt Call");
return new Promise(function(resolve) {
console.log("getBlobAt Promise Created");
window.URL = window.URL || window.webkitURL;
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onload = function () {
console.log("getBlobAt promise completed, resolving...");
var burl = window.URL.createObjectURL(this.response);
console.log("getBlobAt promise completed, resolving2...");
resolve(burl);
console.log("getBlobAt promise completed, resolving3...");
//window.URL.revokeObjectURL(burl); //DO THIS WHEN LOADING NEW SONG
};
console.log("getBlobAt xhr.send() and callback");
xhr.send();
callback(xhr);
//return xhr;
});
}

这是任务图:

            var taskstrings = [endmp3, albumart];
var getBlobTasks = taskstrings.map(function (xurl, i) {
return function () {
console.log("Running a getBlobTask");
return getBlobAt(xurl, function (xhr) {
console.log("getBlobTask callback");
if (g == 0) { //First one is always the mp3 link
current_xhr = xhr;
} else {
current_xhr_album = xhr;
}
}).then(function (res) {
console.log("getBlobTask complete - returning!");
if (g == 0) { //First one is always the mp3 link
current_blob = res;
} else {
current_blob_album = res;
}
return res;
});
};
});

var q = getBlobTasks[0](); // start the first one
for (var i = 1; i < getBlobTasks.length; i++) q = q.then(getBlobTasks[i]);
q.then(function (result) {
//Both globs have been returned
console.log("All getBlobTasks completed!");
setPlayer(current_blob, current_blob_album);
target.attr('class', 'glyphicon glyphicon-pause');
});

它卡在第一个 resolve() 处。这是控制台输出:

Running a getBlobTask
New getBlobAt Call
getBlobAt Promise Created
getBlobAt xhr.send() and callback
getBlobTask callback
getBlobAt promise completed, resolving...
getBlobAt promise completed, resolving2...
getBlobAt promise completed, resolving3...

最佳答案

你有一个 g 变量,你检查 0 但你没有在任何地方定义 g

您没有看到这一点的原因是 native (或 jQuery) promise 不会自动跟踪可能未处理的拒绝。

您可以通过将 .catch 附加到链的末尾来检查错误,看看是否有任何问题。

q.then(function (result) {
...
}).catch(function(e){
console.log(e.message);
console.log(e.stack);
});

这会向您展示问题。

或者,使用更强大的库,如 Bluebird,它会在出现未处理的拒绝时提醒您。

关于JavaScript Promise 卡在 resolve 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23088555/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com