在已履行的承诺中获取未定义的值



我得到了未定义的已兑现承诺值:

0: {status: "fulfilled", value: undefined}
1: {status: "fulfilled", value: undefined}
2: {status: "fulfilled", value: undefined}
3: {status: "rejected", reason: TypeError: Failed to fetch}
4: {status: "rejected", reason: TypeError: Failed to fetch}
5: {status: "rejected", reason: TypeError: Failed to fetch}

如何获取已履行承诺的价值属性数据?

EDIT:我添加了return dataObj语句,但没有用。

var fetchArr = [];
var url1 = "url1";
fetchArr.push(fetch(url1).then(
response => {
response.json().then(function(data) {
var dataObj = {};
dataObj.playlistNumber = i;
dataObj.data = data;
return dataObj;
});
}
));
var url2 = "url2";
fetchArr.push(fetch(url2).then(
response => {
response.json().then(function(data) {
var dataObj = {};
dataObj.playlistNumber = i;
dataObj.data = data;
return dataObj;
});
}
));
var url3 = "url3"
fetchArr.push(fetch(url3).then(
response => {
response.json().then(function(data) {
var dataObj = {};
dataObj.playlistNumber = i;
dataObj.data = data;
return dataObj;
});
}
));

Promise.allSettled(fetchArr).then(function(dataArr) {
console.log(dataArr);
});

// Polyfill for Promise.allSettled
if (!Promise.allSettled) {
const rejectHandler = reason => ({ status: "rejected", reason });
const resolveHandler = value => ({ status: "fulfilled", value });
Promise.allSettled = function(promises) {
const convertedPromises = promises.map(p => Promise.resolve(p).then(resolveHandler, rejectHandler));
return Promise.all(convertedPromises);
};
}

在第一个然后调用的回调中,您不会返回任何内容:

fetchArr.push(fetch(url1).then(
response => {
// There is no return here 
response.json().then(function(data) {
var dataObj = {};
dataObj.playlistNumber = i;
dataObj.data = data;
return dataObj;
});
}
));

因此,如果你这样做,它会起作用:

fetchArr.push(
fetch(url1).then(response => {
// return here
return response.json().then(function(data) {
var dataObj = {};
dataObj.playlistNumber = i;
dataObj.data = data;
return dataObj;
})
})
);

关于连锁承诺的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#chained_promises

相关内容

  • 没有找到相关文章

最新更新